in reply to Re^2: Closing socket handle of child process (complicated?)
in thread Closing socket handle of child process
Thank you for your reply, I didn't post the entire code as I didn't want to take up too much space, instead of posting the entire daemon code, I thought it might be better to post the code for the helper program. This program (helper) acts as an intermediary between my Perl TK program and a forking server which accepts connection requests from helper. helper also has a bidirectional pipe connected to communicate with the TK program. My aim is to send a text command to the helper such as Close_Server which when detected would close the socket connection with the forking server. The problem was that due to blocking I couldnt implement listening to STDIN (this is the piped output from TK program) and listening to the socket in the same while loop without using select (as you suggest). I've tried to use fork which works great but killing the child process does not close the socket, the data still keeps coming through. The only way to stop this is by killing the entire process.
#!/usr/bin/perl # # IP administrator helper. # use 5.005; use IPADM; use IO::Socket; use strict; use vars qw/$sock/; do {print "Usage: helper host port\n"; exit} unless @ARGV == 2; my $neighbourSocket = join ":", $ARGV[0], $ARGV[1]; my $int_count; #Flush back to parent STDOUT->autoflush(1); # unbuffer output $SIG{PIPE} = sub {print "2 Pipe Error.\n$EOF\n"; exit;}; $SIG{TERM} = sub {exit; }; #ignore child processes to prevent zombies $SIG{CHLD} = 'IGNORE'; my $sock = IO::Socket::INET->new( PeerAddr => $ARGV[0], Proto => 'tcp', PeerPort => $ARGV[1]); print +((defined $sock) ? "0 Connect OK:$$" : "3 Connect Failed:$$"), +"\n$EOF\n"; my $kidpid; # split the program into two processes, identical twins die "can't fork: $!" unless defined($kidpid = fork()); # if parent if ($kidpid) { # parent copies the socket to standard output #Read from parent (STDIN), this is received from TK program vi +a a pipe while(<STDIN>) { # if the close server command from TK program is detected, + break from loop last if /Close_Server/; } # kill the child process kill("TERM" => $kidpid); } # if child else { # Loop forever until socket is closed (I cant close it!!) while (1) { # Create array to collect output from server my(@data) = (); # Add the addressing information to start of array push @data, "$neighbourSocket\n"; #collect data from daemon until EOF is reached, at this po +int it can be piped back to TK program while (<$sock>) { push @data, $_; # accumulate command's reply last if /^$EOF$/; } # Catch daemon failure, send output back to TK program for +processing print (/^$EOF$/ ? @data : "4 Daemon Failure\n$EOF\n"); } # whilend } close $sock; exit;
Any guidance would be much appreciated, Paul
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Closing socket handle of child process (shutdown, %SIG)
by tye (Sage) on Jan 03, 2012 at 16:33 UTC |