Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Forking two processes in parallel

by andal (Hermit)
on Mar 07, 2016 at 08:16 UTC ( #1156975=note: print w/replies, xml ) Need Help??


in reply to Forking two processes in parallel

The "fork" call starts another copy of original process. That copy continues running from exactly the same position as the parent. The only difference is the value returned from "fork". So it is obvious, that if one of those 2 processes calls "exec" and the other calls "sleep", then there's no more processes left to start one more bot. So, your second bot is started after the parent kills first bot.

So, to really have 2 processes running independently, you have to come up with some strategy for freeing parent process. In the simplest (and ugly) case, you can use 2 forks to launch 1 bot. Something like

sub fork_bot{ my $arg = shift; my $pid = fork(); die "Can't fork: $!\n" unless defined $pid; return if $pid != 0; $pid = fork(); die "Can't fork: $!\n" unless defined $pid; if($pid == 0){ exec($arg->{bot}) or die "Can't start $arg->{bot}: $!\n"; } sleep $arg->{runtime}; kill 1, $pid or die "Can't kill $arg->{bot}: $!\n"; exit(0); }
Your main code, after starting bots, may do then something like
my $chld; do{ $chld = wait(); }while($chld >= 0);
Again, this code will work, but it is not very useful. The bots that you start this way won't be able to communicate with each other or with the parent. The style of communication (one way or both ways) shall define the complexity of the system that you have to design.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2022-11-28 17:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?