in reply to Sockets

Turn on autoflushing. It works OK like this on my NT box (fork() is there, too - kudos to ActiveState for fork implementation!).

#!/usr/bin/perl use IO::Socket; $SIG{CHLD} = sub {wait()}; # turn autoflushing on $| = 1; $main_sock = new IO::Socket::INET( LocalHost => '127.0.0.1', LocalPort => 6666, Listen => 5, Proto => 'tcp', Reuse => 1) or die $!; $line = ""; while ($new_sock = $main_sock->accept()) { $pid = fork(); die "Cannot fork: $!" unless defined($pid); if ($pid == 0) { # Child process while (defined ($buf = <$new_sock>)) { print "Client said: $buf\n"; } exit(0); } else { $line = <STDIN>; print $new_sock "$line"; } }

NOTE: (added to node later) - sorry - I did not get your point right - the script does not remedy the problem you talked about - however, turning autoflushing on is a good idea for networking code, anyway.

Christian Lemburg
Brainbench MVP for Perl
http://www.brainbench.com

Replies are listed 'Best First'.
Re: RE: Sockets
by meonkeys (Chaplain) on Apr 24, 2001 at 13:57 UTC
    Curious, what did this snippet do for you?
    $SIG{CHLD} = sub {wait()};

    and what about this part?
    } else { $line = <STDIN>; print $new_sock "$line"; }


    Also, how do you get the server to hang up on the client? I tried something like:
    chomp($buf); exit(0) if ($buf eq 'q');

    But the client (I use telnet) connected to the server holds fast until I hit <CR> on the console that's running the server.

      Well, I just copied the code over from the question to illustrate, but ...

      • $SIG{CHLD} = sub {wait()};

        This ensures proper cleanup of child resources after child terminates. "When a process exits, its parent is sent a CHLD signal by the kernel and the process becomes a zombie until the parent calls wait or waitpid. If you start another process in Perl using anything except fork, Perl takes care of reaping your zombied children, but if you use a raw fork, you're expected to clean up after yourself." (from Camel, 3rd ed.). I don't know really if this is needed on Win32, but it is supported, since "wait() and waitpid() can be passed a pseudo-process ID returned by fork(). These calls will properly wait for the termination of the pseudo-process and return its status." (from ActiveState Perl docs).

      • The else clause is the main server process. It blocks reading one line from STDIN and sends that to the newly forked socket connection.

      This is probably not the best example code for writing servers and clients. Have a look at the Perl Cookbook, chapter 17.

      Christian Lemburg
      Brainbench MVP for Perl
      http://www.brainbench.com

        Ah. Thanks! I will hop back on to the Camel's back.