Some time you may see this problem, your program forks children, but the dead children accumulate, fill up your process table, and aggravate your system administrator.

Solution #1

If you don't need to record the children that have terminated, use


To avoid accumulating dead children, simply tell the system that you ar not interested in them by setting $SIG{CHLD} to "IGNORE". If you want to kno wwhich children die and when, you'll need to use waitpid.

Solution #2

To keep better track of decreased children, install a SIGCHLD handler to call waitpid:

use POSIX ":sys_wait_h";
sub REAPER {
      my $stiff;
      while (($stiff = waitpid(-1,&WNOHANG)) > 0 ){
            #do something with $stiff if you want

Here comes two questions, why waitpid ? why there is loop?

Why waitpid?

The waitpid function reaps a single process. Its first argument is the process to wait for(-1 means any process), and the second argument is a set of flags. We use the WNOHANG flag to make waitpid immediately return 0 if there are no dead children.

The wait function also reaps children, but it does not have a non blocking option. If you inadvertently call it when there are running child processes but none have exited, your program will pause until there is a dead child.

Why looping?

Because the kernel keeps track of undelivered signals using a bit vector, one bit per signal, if two children die before your process is scheduled, you will get onlya single SIGCHLD. You must always loop when you reap in a SIGCHLD handler, and so you can't use wait.






Comments powered by CComment