I’ve written a C++ application that waits until an event occurs (e.g. wait for incoming connection). After that event occured, it will continue by forking a child process that handles that event.
So, my code looks essentially like this:
int main(void) { while(1) { Event e = waitUntilSomethingHappens(); // blocks execution until event occurs pid_t pid = fork(); if (pid == 0) { doChildStuff(e); exit(0); return 0; } } return 0; }
My expectation now was that the child process will terminate (because of exit(0)
and/or return
). Indeed, it leaves the while loop, but it seems not to be terminated. When I hit ps -e
, both processes are displayed, whereas the child process is marked as <defunct>
.
Why doesn’t it disappear? What can I do to let it disappear?
Advertisement
Answer
You have to use one of the wait
calls to get a notification for the state change of the child.
From the manual:
A child that terminates, but has not been waited for becomes a “zombie”. The kernel maintains a minimal set of information about the zombie process (PID, termination status, resource usage information) in order to allow the parent to later perform a wait to obtain information about the child. As long as a zombie is not removed from the system via a wait, it will consume a slot in the kernel process table, and if this table fills, it will not be possible to create further processes. If a parent process terminates, then its “zombie” children (if any) are adopted by init(8), which automatically performs a wait to remove the zombies.