home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Perl CookbookPerl CookbookSearch this book

17.11. Forking Servers

17.11.2. Solution

Fork in the accept loop, and use a $SIG{CHLD} handler to reap the children.

# set up the socket SERVER, bind and listen ...
use POSIX qw(:sys_wait_h);

sub REAPER {
    1 until (-1 =  = waitpid(-1, WNOHANG));
    $SIG{CHLD} = \&REAPER;                 # unless $]>= 5.002
}

$SIG{CHLD} = \&REAPER;

while ($hisaddr = accept(CLIENT, SERVER)) {
    next if $pid = fork;                    # parent
    die "fork: $!" unless defined $pid;     # failure
    # otherwise child
    close(SERVER);                          # no use to child
    # ... do something
    exit;                                   # child leaves
} continue { 
    close(CLIENT);                          # no use to parent
}


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.