in reply to TCP Server using fork to accept multiple requests

My preferred way of doing this (although I'd rather use an async package).

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11146183 use warnings; use IO::Socket::INET; $SIG{CHLD} = 'IGNORE'; # NOTE my $socket = new IO::Socket::INET ( LocalHost => '0.0.0.0', LocalPort => '5000', Proto => 'tcp', Listen => 5, Reuse => 1); die "cannot create socket $!n" unless $socket; while( 1 ) # NOTE because you don't want Interrupted system call to ex +it the server { if( my $new_sock = $socket->accept() ) { if( my $pid = fork() ) { # parent, nothing to do } elsif( defined $pid ) { print while <$new_sock>; # child exit; } else { die "Cannot fork: $!"; } } elsif( $! =~ /Interrupted system call/i ) { # just ignore } else { die "$! on accept call"; # some serious error } }

Replies are listed 'Best First'.
Re^2: TCP Server using fork to accept multiple requests
by NERDVANA (Priest) on Aug 20, 2022 at 14:40 UTC
    # parent, nothing to do
    Um, except close the socket which is fairly important.

    Nevermind, This is perl, not C, I'm a moron.

      The socket is closed when $new_sock goes out of its scope, which is the "if" statement, so the socket IS closed when the outer "while" repeats. All the parent has to do is exit the "if".

        Post updated. Sorry for the noise.