#!/usr/bin/perl -w use strict; use IO::Socket; use Sys::Hostname; use POSIX qw(:sys_wait_h); # choose either. ignore will work, REAPER won't $SIG{CHLD} = 'IGNORE'; # still loathe sysV $SIG{CHLD} = \&REAPER; # still loathe sysV my $sock = new IO::Socket::INET( LocalHost => '127.0.0.1', LocalPort => 9898, Proto => 'tcp', Listen => 10, ReuseAddr => 1 ); $sock or die "no socket :$!"; print STDERR "Parent $$: Server up\n"; while ( my $new_sock = $sock->accept() ) { $new_sock->autoflush(1); my($buf, $kid); if ($kid = fork) { print STDERR "Parent $$ after fork\n"; } else { die "fork: $!" unless defined $kid; # child now... print STDERR "Child $$: started\n"; # read from client $buf = <$new_sock>; chomp $buf; print "Child $$: Read from client: $buf\n"; # do something (sleep some random secs) my $secs = int(rand(srand())*10)+1; sleep $secs; print $new_sock "READY\n"; print "Child $$: Sent READY, closing\n"; exit 0; } } print STDERR "Parent $$: Should never get here\n"; ######################################################## sub REAPER { ######################################################## my $child; while (($child = waitpid(-1,WNOHANG)) > 0) { print "Parent $$: Reaped $child\n"; } $SIG{CHLD} = \&REAPER; # still loathe sysV }