by gpm · 5y ago · 0 comments
Traditionally processes have reaped dead children by waiting on them, the problem with this is it's a synchronous operation that blocks a thread per child.
The only historical non-blocking solution was to listen for signals. Signals are great and all, except that the kernel will sometimes (unavoidably) merge multiple signals together, preventing you from getting a list of dead children. This is problematic if you want to know exactly which children died.
Linux 5.3 introduced a third system to listen for dead children, pidfd. It's a file descriptor which you can pass to epoll to know when a specific child dies. This is great, but it didn't yet support O_NONBLOCK, which meant that to use it in asynchronous (rust) code we need to create an extra thread which just sits around listening for it.
Linux 5.10 brings the ability to make this fd non blocking, so we can integrate this seamlessly into async event loops. Here's some code of mine that does that: https://github.com/gmorenz/async-transpiled-xv6-shell/blob/m...
Thanks to Christian Brauner, Josh Triplett, and Oleg Nesterov: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/lin...
That said, if your child process has genuine potential to acting adversarially, I don't believe even pidfds would be enough; you'll need to make sure it doesn't spawn e.g. a child process to break away.
However, I would guess that's not your actual use case? Rather, I'd assume you're trying to prevent against accidents. If you're in this boat like I'm assuming, I'd suggest thinking over whether the scenario you proposed is actually plausible. The only real-world instances I've seen a process playing "games" with file descriptors it did not previously open itself are (a) closing FDs after a fork, and (b) user code in a shell, doing something like exec 2>&3 or whatever. I assume you're worried about the latter given the former isn't relevant. In that case, you could work around it via dup2() after you fork(), by duping into a random high FD that nobody would be likely to mess with (like a random high number plus its own PID). This should solve it for practical purposes.
Not that you shouldn't use pidfds necessarily, but I'm just throwing these out there because I've been in this situation before and these might help you solve your problem on other systems that don't support that.
as a c2rust contributor, this made me smile :) thx friend!
Wouldn't the wait syscall wait for any child?
Not sure why this would not work for the OP or miss some process terminations due to merged SIGCHLD signals? I guess using pidfd may be more straightforward, but I don't think this was some unsolved problem previously.
Of course if I want to deploy code like this in any serious way I'll have to implement another solution than non blocking pidfds...