I got the PID of a process and I need to check if it is a zombie using POSIX system calls in C. How should I do that?
The problem I'm having is that I have a process and it forks into many children, the children all do execs and sometimes I want to do the exec in background so I can't really wait() the children that go in background. I could wait() periodically (once in my main loop) but I need to know which processes are zombie so my father process doesn't hang while waiting for children that are not going to end soon.
If you are curious, I'm building a unix shell and it is in the shell nature to have the children processes behaving asynchronously.
You can't check whether a process is a zombie with pure POSIX calls - except where you're the parent process, and reaping it with a wait
family call. So you'll have to find a good place to wait for the child.
One option is to set a SIGCHLD
handler and do a waitpid(0, &status, WNOHANG)
there. Be sure to loop until it no longer finds any processes - if two children die within a short interval, you may only get one SIGCHLD
.
Another option is to double fork - that is, fork()
, have the child (call it child A) fork again, have the second child (child B) exec. Then child A immediately exits. Meanwhile the parent is wait()
ing for child A. Once child A is gone, the system's init process will take care of reaping child B when it eventually dies. This method is simpler, but your shell will have no way of knowing when child B dies, so if you need that information, use the former method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With