skerr1 has asked for the wisdom of the Perl Monks concerning the following question:
SunOS 5.6 Perl 5.6.1
I have the following:
$SIG{'CHLD'} = 'IGNORE'; open(STDOUT, ">>my.log"); STDOUT->autoflush(1); open(STDERR, ">>my.log"); STDERR->autoflush(1); my $sock = new IO::Socket::INET (LocalHost => 'foo.com', LocalPort => 1234, Proto => 'tcp', Listen => 5, ReuseAddr => 1 ); $sock or die("Failed to create sock: $!."); ONE: while ( 1 ) { my $new_sock = $sock->accept; if (!defined($new_sock)) { print(STDERR "Warning: Bad connect.\n"); next ONE; } if ( ! defined($child = fork) ) { print("Could not fork: $!.\n"); exit(1); } $child && next; <do something as the child> shutdown($new_sock,2); close($new_sock); exit(0); } # End ONE close($sock);
My questions are:
1. For the close($new_sock);, should I be checking the return value for this. I wasn't sure why a close on a socket connection would fail.
2. For the close($sock);, is this necessary/useful and can/should I check for a failure? Also, would shutdown($sock,2); do anything useful? I didn't think so, but I saw it while googling for example code.
3. If the child process is executing a command like system("echo Hello");, I need to reap child processes before closing the forked child process so as not to leave "zombies" right? Or is my handling that via capturing the CHLD signal ($SIG{'CHLD'} = 'IGNORE';) before I even start up the socket sufficient? I wasn't sure I needed to do one of these:
while ( my $child_process = waitpid(-1,WNOHANG) > 0 ) { }
before I close the child each time.
4. In Perl 5.6.1, after each accepted connection do I need to reset STDERR and STDOUT that I set prior creating the socket? Previously in Perl 5.005_02 I was having to reset these with each new connection. If that's the same, can someone tell me why?
I think that's it. I thank you for any help you can offer.
Regards,
NOTE: Updated to remove filehandle comment so we can better focus on the questions. Thanks -sk
2005-10-21 Retitled by planetscape, as per Monastery guidelines
Original title: 'Socket'
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Handling sockets in a server
by blazar (Canon) on Oct 21, 2005 at 09:11 UTC | |
by skerr1 (Sexton) on Oct 21, 2005 at 12:58 UTC | |
by tbone1 (Monsignor) on Oct 21, 2005 at 13:18 UTC | |
by skerr1 (Sexton) on Oct 21, 2005 at 14:55 UTC | |
by blazar (Canon) on Oct 21, 2005 at 13:16 UTC | |
by skerr1 (Sexton) on Oct 21, 2005 at 17:25 UTC | |
by BrowserUk (Patriarch) on Oct 21, 2005 at 17:56 UTC | |
by skerr1 (Sexton) on Oct 21, 2005 at 18:23 UTC | |
by BrowserUk (Patriarch) on Oct 21, 2005 at 19:14 UTC | |
by skerr1 (Sexton) on Oct 23, 2005 at 03:07 UTC | |
|