Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a process with a pid X is a zombie?

Tags:

c

posix

process

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.

like image 580
Hoffmann Avatar asked Dec 23 '22 08:12

Hoffmann


1 Answers

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.

like image 188
bdonlan Avatar answered Jan 05 '23 22:01

bdonlan