So I want to do the following:
Set up a daemon that forks a bunch of processes.
So the Daemon forks a bunch of processes then forks another bunch of processes
the problem is the child processes might take a long time to exit. How do I prevent zombie children if the parent process has other work to do despite forking children?
The parent process (the daemon) does something like this:
while(true)
{
SQL QUERY EXECUTED
while(mysql_fetch_array)
{
Fork children
}
}
The problem is how can I wait for the children processes to exit if the parent process has to do other work besides forking children and if the children take a long time to exit.
I am using the System daemon PEAR function to create the daemon and the pcntl_fork
function to create the processes.
I don't remember where I saw this:
Parent forks child
Waits until child is dead (this won't take long, see ahead)
Goes on
Child does only 2 things:
Forks a grandchild
Exits
Grandchild does whatever work is needed
Exits
The trick is that when the Granchild dies, its parent (one of your Children) is already dead. But someone has to be notified for the death. It appears that in Linux systems, it's not the grandparent that is notified but the grand-grand-...-grandparent of all. And because that process knows its job, it periodically checks for dead children and does not allow them to become zombies.
Here's a link with explanation: http://fixunix.com/unix/533215-how-avoid-zombie-processes.html
When a process's parent terminates, the "init" process takes over as its parent. So when the child process exits, the grandchild loses its parent, and is adopted by init. Init always reaps its dead children, so they don't become zombies.