Child reaping update:
After yet more experimentation with this fabulously educational node I did what was necessary to make it run via init.d based on this node.
I soon discovered that when a client was streaming and the parent was killed via the init.d script, the child serving the active client remained running and required manual killing.
To fix this problem I kept track of the children in the code and provided a clean-up routine when the script received a TERM signal. Below I list the $SIG{"TERM"} code to catch the TERM signal and 2 extra lines inside the main while loop to track the children as marked between the # >> tags:
# somewhere before the socket is used
my %kids;
$SIG{"TERM"} = "cleanup_and_exit";
sub cleanup_and_exit {
my $sig = @_;
foreach my $kid (keys %kids) {
#reap them
warn("Failed to reap child pid: $kid\n") unless kill
+ 9, $kid;
}
# it's a good idea to exit when we are told to
exit(0);
}
# -- bits left out here --
#wait for connections at the accept call
while (my $connection = $listen_socket->accept)
{
my $child;
# perform the fork or exit
die "Can't fork: $!" unless defined ($child = fork());
if ($child == 0)
{ #i'm the child!
#close the child's listen socket, we dont need it.
$listen_socket->close;
#call the main child rountine
play_songs($connection);
#if the child returns, then just exit;
# >>
undef $kids{$child};
# >>
exit 0;
}
else
{ #i'm the parent!
# >>
$kids{$child} = 1;
# >>
#who connected?
warn "Connecton recieved ... ",$connection->peerhost,"\n";
#close the connection, the parent has already passed
# it off to a child.
$connection->close();
}
#go back and listen for the next connection!
}
# -- bits left out here --
I'm not a great Perl programmer, but this works flawlessly on my Debian system and has provided my an exceptional motivational tool to start learning socket programming. I hope I havne't overlooked too much error checking or done anything dangerous with my reaping and this can be of some use to someone.
Thanks again.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|