Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Please describe to me the behavior of the following code. Why does it "never reach here"?
Do the parent and child processes take turns running indefinitely?

my $socket; my $line; my $child_pid; $socket = IO::Socket::INET->new ( PeerAddr => 'server.com', PeerPort => 1247, Proto => "tcp", Type => SOCK_STREAM ) or die "Could not create client.\n"; unless (defined($child_pid = fork())) {die "Cannot fork.\n"}; if ($child_pid) { while($line = <>) { print $socket $line; } } else { while ($line = <$socket>) { print "Other side: $line"; } } # never reach here -- WHY NOT?

Edit kudra, 2002-04-23 Changed title

Replies are listed 'Best First'.
Re: Seeking explanation of IO::Socket behaviour
by dws (Chancellor) on Apr 22, 2002 at 02:44 UTC
    The "# never reach here" line is reached on the parent process when the input stream reaches EOF (which might involve typing ^D if the input stream is the terminal). Assuming that "# never reach here" is the end of the script, falling past it implicitly closes the socket from the parent side, which will cause the child process to see EOF on the socket. The child then hits the "# never reach here" line.

    Unless I'm missing some subtle point, the "# never reach here" comment is a lie.

      I don't think dws missed anything, but the Anonymous Monk forgot to mention: what is being fed to the parent's stdin? If this is run from the command line without (redirection from) a file name, and without a preceding pipeline process, it will run endlessly until the person who entered the command has the presence of mind to type in data, then type in "^D" (on unix) or "^Z" (on dos/windows) to signal the end of stdin.
        Thanks for your wisdom. I really needed to know if the program will run indefinitely. Now I know it will. Thanks again.
      Thanks for that piece of wisdom. It's a big help.