Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Keeping children alive persistiently, intelligently

by peterdragon (Beadle)
on Feb 09, 2008 at 09:21 UTC ( [id://667158]=note: print w/replies, xml ) Need Help??


in reply to Keeping children alive persistiently, intelligently

POE is a good choice for the parent. It makes it easy to write event-driven code that handles state changes and timed events.

POE is single threaded, however, so you definitely need to fork() any workers that might block. There's some example start/stop code at Re: Perl Background processes in Windows. Remove the setsid() call from that and the children will stay in the parent process group and die when it does. You should also consider what you're doing with Stdin/Stdout/Stderr in the child processes - going to parent's tty, or to log file or /dev/null? Also if you interrupt with CTRL-C you probably need tidy up code.

Following is an example of using POE to control start/stop. You would need to make it more sophisticated to handle your rules for the list of parameters and the respawn intervals. E.g. stash the date/time of last exit against entries in your list and take account of that in the spawner.

#!/usr/bin/perl use strict; use warnings; # POE checking/debug levels sub POE::Kernel::ASSERT_DEFAULT { 0 } # DATA, EVENTS, FILES, RETVALS, +USAGE sub POE::Kernel::ASSERT_EVENTS { 1 } sub POE::Kernel::ASSERT_USAGE { 1 } sub POE::Session::ASSERT_STATES { 1 } use POE; use POSIX; my $num_kids = 8; my %kid_pids; main(); END { do_end(); } sub do_end { # FILL HERE exit(0); } sub main { # catch CTRL-C interrupt to tidy up cleanly $SIG{QUIT} = $SIG{INT} = $SIG{HUP} = \&do_end; POE::Session->create ( inline_states => { _start => sub { print "Starting\n"; $_[KERNEL]->sig('INT', 'signal_handler'); $_[KERNEL]->delay(reaper => 1 ); $_[KERNEL]->delay(spawner => 1 ); }, _stop => sub {}, signal_handler => sub { my ($kernel, $sig) = @_[KERNEL, ARG0]; print "caught SIG$sig\n"; do_end(); }, reaper => sub { $_[KERNEL]->delay(reaper => 1); while ( (my $pid = waitpid(-1, POSIX::WNOHANG)) > -1 ) { my $exit_status = $? / 256; delete $kid_pids{$pid}; print "child $pid died status $exit_status\n"; } }, spawner => sub { $_[KERNEL]->delay(spawner => 1); # start new kid if slot free if (scalar keys %kid_pids < $num_kids) { my $pid = start_child(); if ($pid > 0) { $kid_pids{$pid} = 1; print "child $pid started\n"; } } }, }, ); $poe_kernel->run(); } sub start_child { # FILL HERE return $pid; }

Regards, Peter

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-04-19 23:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found