This is a fairly robust forking server, put together from perlipc and this post in selfHTML (german)

#!/usr/bin/perl -w + use strict; + use IO::Socket; + use POSIX qw(:sys_wait_h); + use Errno; + + my $waitedpid = 0; + my $terminated_pid = 0; + sub logmsg { print scalar localtime() . " $$: @_\n" } sub REAPER { local $!; while (($waitedpid = waitpid(-1,WNOHANG)) > 0 && WIFEXITED($?) +) { $terminated_pid = $waitedpid; + logmsg "Parent: Reaped $waitedpid" . ($? ? " with exit + $?" : ''); } $SIG{'CHLD'} = \&REAPER; } $SIG{'CHLD'} = \&REAPER; my $sock = new IO::Socket::INET( LocalHost => '127.0.0.1', LocalPort => 9898, Proto => 'tcp', Listen => 10, ReuseAddr => 1 ); $sock or die "no socket :$!"; logmsg "Parent $$: Server up"; STDERR->autoflush(1); STDOUT->autoflush(1); while (1) { my $new_sock = $sock->accept() || do { # try again if accept() returned because a signal was received next if $!{EINTR}; die "accept: $!"; }; $new_sock->autoflush(1); my($buf, $kid); if ($kid = fork) { # parent closes the client since # it is not needed logmsg "Parent after forking"; } else { die "fork: $!" unless defined $kid; # child now... logmsg "Child: started"; # read from client $buf = <$new_sock>; chomp $buf; logmsg "Child: Read from client: $buf"; my $secs = int(rand(srand())*10)+1; sleep $secs; print $new_sock "READY\n"; logmsg "Child sent READY, closing"; $new_sock->close; exit 0; } } logmsg "Parent: Should never get here";

Regards,
svenXY

In reply to SOLVED: Re: TCP Client-Server: Server exits though it shouldn't by svenXY
in thread TCP Client-Server: Server exits though it shouldn't by svenXY

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.