#!/usr/local/bin/perl use strict; use IO::Socket qw(:DEFAULT :crlf); use IO::File; use POSIX 'WNOHANG'; use POSIX 'setsid'; use POSIX 'sys_wait_h'; my $port = 1426; my $socket = IO::Socket::INET->new( Proto => 'tcp', LocalPort => $port, Listen => 5, Reuse => SO_REUSEADDR, Type => SOCK_STREAM ) or die "Can't create listen socket: $!"; my $pid = become_daemon(); my $children = 0; $SIG{CHLD} = \&reaper1; while (my $conn = $socket->accept) { print "Received a request from a client....\n"; defined (my $child = fork()) or die "Can't fork: $!"; $children++; print "POST FORK: me = $$ child= $child\n"; if ($child == 0) { #my $x = become_daemon(); #print "my child is $x\n"; print "I am the child $$\n"; do_child($conn); exit(0); } else { print "I am the parent $$... waiting for next request\n"; } } sub become_daemon { print "Forking Daemon\n"; print "My pid is $$\n"; die "Can't fork" unless defined (my $child = fork); print "Forked... my pid is $$\n"; print "child pid is $child\n"; exit 0 if $child; # setsid(); open(STDIN, "/dev/null"); open(STDERR, ">&STDOUT"); chdir("/"); umask(0); return $$; } sub reaper1 { #my $sig=shift; my $kid = waitpid(-1,&WNOHANG); while (my $kid > 0) { warn "REAPER: Reaped child with PID $kid\n"; } $SIG{CHLD} = \&reaper1; } sub do_child { my $connection = shift; my $resp = <$connection>; print "FromClient: $resp"; my $parent = getppid(); for (1.. 10) { print $connection "pid $$ parent=$parent Sending number $_\n"; sleep 1 } print $connection "All done\n"; print "All done\n"; #$connection->close; return; } #### #!/usr/local/bin/perl use IO::Socket; my $port = 1426; my $host = myhost; our $socket = IO::Socket::INET->new( Proto => 'tcp', PeerAddr => "$host", PeerPort => "$port" ) or die "Can't create listen socket: $!"; $socket->send("begin\n"); while(<$socket>) { chomp; print $_ . "\n"; } close $socket;