| Tom Phoenix 2006-01-10, 4:02 am |
| On 1/5/06, Rahul <ftp1234@gmail.com> wrote:
> if (fork() =3D=3D 0){
Because your process table can become full and temporarily prevent
forking new processes, you should check the return value of fork
whenever you're making more than N processes. The value of N depends
upon a number of factors, so I generally assume N=3D0. Most of the time,
I just call this safe_fork routine in place of fork, since this
handles the retries for me automatically.
sub safe_fork () {
use Errno;
my $retries =3D 10;
while ($retries--) {
my $rv =3D fork;
return $rv if defined $rv; # it worked
return unless $retries;
return unless $!{EAGAIN};
sleep 3;
}
die "Well, how did I get here?";
}
> now, since the parent does not wait upon the child to finish (i don't wan=
t
> it to explicitly wait, since i want to have multiple children run
> simultaneously), so there are lot of zombie children left, thereby making
> the system slow, and finally hang.
>
> i researched a lot, there are 2 ways to avoid this.
>
> 1) $SIG{'CHLD'} =3D 'IGNORE';
> 2) $SIG{'CHLD'} =3D sub { while(waitpid(-1,WNOHANG)>0) {} } ;
There are other ways, too. One popular way is the "double-fork" trick.
Instead of making a child process, you make a grandchild process. That
is, the first fork makes a child process which forks again to make the
grandchild, then exits. The grandchild does the work, the parent
continues running. Because the grandchild process's parent process is
gone, the responsibility for reaping the zombie passes to init(8). At
least, that's what happens on most Unix-like systems.
If you're starting many such processes, you can use one child process
to start a number of grandchild processes at once, limited of course
by your system's abilities. That's more efficient than starting just a
single grandchild per child process.
And with all this talk about fork, I have to ask everyone playing
along at home whether they know what you can get when your program has
both a fork and an infinite loop? If you're the only user on your box,
you can do whatever you want. But other users may not appreciate a
fork bomb.
http://catb.org/~esr/jargon/html/F/fork-bomb.html
Cheers!
--Tom Phoenix
Stonehenge Perl Training
|