Bloehdian has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
the following code is the start off for a program which should read data from one socket to another socket using fork and pipe. The source socket is currently "simulated" by a for-loop generating lines of data (in the parent process), which are send over the pipe to the child process which connects to a tcp-socket and in turn sends the data to this socket.
But the latter seems to work just one time, then the child is silent.
What am I doing wrong?
Is the fork/pipe approach feasible at all when it comes to loops (with constantly closing the file handles)?
#/usr/bin/perl use IO::Socket::INET; pipe( READER, WRITER ); WRITER->autoflush(1); if ( ! defined ( $pid = fork() ) ) { die( "Cannot fork!: $!" ) } elsif ( $pid == 0 ) { $line = ''; # A line of data read # Connect to socket # $connected = 0; while ( 1 ) { eval { undef $socket; $socket = IO::Socket::INET->new ( PeerHost => '127.0.0.1', PeerPort => '7776', Proto => 'tcp' ); }; if ( $@ ) { print "$@\n" } if ( defined $socket ) { print( "Connected!\n" ); $connected = 1; } else { print( "Could not connect!\n" ); $connected = 0; } while ( $connected ) { close WRITER; $line = <READER>; close READER; print( "CHILD: Received line $line\n" ); eval { if ( defined $socket->send( $line ) ) { shutdown( $socket, 1 ); } else { $connected = 0; } }; } } } else { # Parent # for ( $i=1; $i<=1000000; $i++ ) { $line = "-- " . $i . " --"; print( "PARENT: Going to transfer line $line\n" ); close READER; print WRITER $line; close WRITER; sleep 1; } }
The output is
Any help appreciated! Cheers BloehdianPARENT: Going to transfer line -- 1 -- Connected! CHILD: Received line -- 1 -- CHILD: Received line PARENT: Going to transfer line -- 2 -- PARENT: Going to transfer line -- 3 -- PARENT: Going to transfer line -- 4 -- PARENT: Going to transfer line -- 5 -- PARENT: Going to transfer line -- 6 -- PARENT: Going to transfer line -- 7 -- PARENT: Going to transfer line -- 8 -- PARENT: Going to transfer line -- 9 -- ^C
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: pipe used to send continuously to a TCP Socket does not work
by tybalt89 (Monsignor) on Oct 11, 2016 at 20:22 UTC | |
|
Re: pipe used to send continuously to a TCP Socket does not work
by talexb (Chancellor) on Oct 11, 2016 at 18:58 UTC | |
by Bloehdian (Beadle) on Oct 11, 2016 at 19:14 UTC |