Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: TCP Server using fork to accept multiple requests

by tybalt89 (Monsignor)
on Aug 17, 2022 at 09:22 UTC ( [id://11146188]=note: print w/replies, xml ) Need Help??


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 (Deacon) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11146188]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-19 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found