Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Forking two processes in parallel

by Tanktalus (Canon)
on Mar 06, 2016 at 02:25 UTC ( [id://1156903]=note: print w/replies, xml ) Need Help??


in reply to Forking two processes in parallel

Your fork_bot doesn't return until it has slept.

You need to fork both off, and manage the sleep events in the parent. And the parent has to wait around for the children to finish, else the parent exiting may also terminate its children.

Personally, I've found that using an event manager simplifies this greatly. Completely untested code:

use strict; use warnings; use AnyEvent; use AnyEvent::Util; sub fork_bot { my $arg = shift; my $pid; my $cv = AnyEvent::Util::run_cmd( $arg->{bot}, '$$' => \$pid, ); my $w; $w = AE::timer( $arg->{runtime}, 0, sub { print "Killing $arg->{runtime} - timeout +\n"; kill INT, $pid; $w = undef; } ); $cv } my $bot1 = fork_bot({ bot => ['./cfbot.pm', '--debug'], runtime => 60 +}); my $bot2 = fork_bot({ bot => ['./cfbot_tester.pm'], runtime => 20 +}); $bot1->recv; $bot2->recv; # continue with program
Now, I'm sure you can do this equally as well with other event handlers, or with threads. This is just what I'm used to.

Coro can simplify this a bit further, but at this point it's not enough to warrant, IMO. (It would invert the timeout into a Coro-version of sleep, but I don't think that's a huge benefit here.)

Also, we can use this to also clean up the $w watcher, to eliminate that timer if the child exits before the timer runs out.

Hope that helps.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-03-28 13:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found