Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

exit(0) isn't killing the children in this. On the first connect, it creates a new child (I assume,) says "Hi!", then does nothing. The process still has two threads even after it would appear that the child would be exitting. What am I doing wrong? (The while loop was originally from the Cougar book but has since been chopped down to the bare minimums.)
my $listener = IO::Socket::INET->new(LocalPort => 12345, Listen => 1) || die "Cannot creat +e socket\n"; while ($client = $listener->accept()) { $pid = fork(); die "Cannot fork: $!" unless defined($pid); if ($pid == 0) { print "Hi!"; exit(0); } }

Replies are listed 'Best First'.
Re: exit isn't killing children
by chromatic (Archbishop) on Dec 16, 2002 at 03:00 UTC

    As the documentation for fork states, you probably need to wait on the child processes (not threads; be careful with the terminology):

    If you "fork" without ever waiting on your children, you will accumulate zombies. On some sys­tems, you can avoid this by setting "$SIG{CHLD}" to "IGNORE". See also the perlipc manpage for more examples of forking and reaping moribund children.
Re: exit isn't killing children
by pg (Canon) on Dec 16, 2002 at 03:30 UTC
    Not a direct solution for your problem, but I noticed something that you might want to improve for a better style, and to show a clear understanding of socket programming.
    1. In the child process, $listener is not useful at all, so the child process should close it after being forked. Don't worry, this will not close the $listener in the parent process.
    2. Similarly, $client is not useful in the parent process, so the parent process should close each instance of $client, after it forked the child process for that particular $client. Again, don't worry, this will not close the $client in the child process.
Re: exit isn't killing children
by VSarkiss (Monsignor) on Dec 16, 2002 at 03:21 UTC

    exit(0) isn't killing the children in this.
    exit never kills children. It tells the current process to go away.

    What am I doing wrong?
    It's impossible to answer that without knowing what you're trying to do. As you correctly noted, this program accepts a connection, then does nothing. But your note sounds like you were expecting it to do something else. What were you expecting? If you describe that more fully, it'll be a lot easier to help.