#!/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
}
####
#!/usr/bin/env perl
use strict;
use warnings;
use IO::Socket;
my $remote = IO::Socket::INET->new( Proto => "tcp",
PeerAddr => '127.0.0.1',
PeerPort => "9898",
);
unless ($remote) { die "cannot connect" }
$remote->autoflush(1);
print $remote "client $$\n";
while ( <$remote> ) { print;last; }
close $remote;
print "Socket gone, exiting\n";
##
##
Parent 28877: Server up
Parent 28877 after forking
Child 28949: started
Child 28949: Read from client: client 28948
Child 28949: Sent READY, closing
Parent 28877: Reaped 28949
Parent 28877: Should never get here
##
##
use Win32::Console::ANSI;
$|=1;
print "\e[s"; # store 1st pos otherwise it will clear the whole screen
for ( 'a'x300, 'b'x200, 'c'x100) {
print "\e[u\e[0J"; # go to stored pos, del to end
print "\e[s$_"; # store pos, print output
sleep 3;
}