#/usr/bin/perl use warnings; use IO::Socket::INET; use Scalar::Util; $port = '7777'; if ( defined $ARGV[0] ) { $port = $ARGV[0] } $SIG{ 'TERM' } = $SIG{ 'INT' } = sub { print( "died() or caught TERM/INT\n" ); exit(); }; $SIG { 'PIPE' } = 'IGNORE'; pipe( $reader, $writer ); $writer->autoflush(1); if ( ! defined ( $pid = fork() ) ) { die( "Cannot fork!: $!" ) } elsif ( $pid == 0 ) { # Child # $line = ''; # A line of data to be read # Connect to socket # $connected = 0; while ( 1 ) { eval { undef $socket; $socket = IO::Socket::INET->new ( PeerHost => '127.0.0.1', PeerPort => $port, Proto => 'tcp' ); }; if ( $@ ) { print "$@\n" } if ( defined $socket ) { print( "Connected!\n" ); $connected = 1; } else { print( "Could not connect!\n" ); $connected = 0; die(); } close $writer; while ( $connected ) { defined ( $line_2 = <$reader> ) or last; print( "CHILD: Received line $line_2\n" ); eval { if ( defined $socket->send( $line_2 ) ) { print ( "CHILD: \$socket->send() successful: $line_2\n") ; #shutdown( $socket, 1 ); $response = ""; $socket->recv($response, 1024); print "CHILD: received response: $response\n"; } else { print( "Not connected!\n" ); $connected = 0; } }; if ( $@ ) { print( "CHILD: error when trying to send(): $@" ) } } close $reader; } } else { # Parent # close $reader; for ( $i=1; $i<=5; $i++ ) { $line = "-- " . $i . " --"; print( "PARENT: Going to transfer line $line\n" ); eval { if ( print $writer "$line\n") { print ( "PARENT: Successfully pushed to child!\n" ); } }; if ( $@ ) { print( "$@\n" ) } sleep 1; } close $writer; print "PARENT: closed writer, waiting for child to exit\n"; 1 while wait > 0; }