Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Parallel::ForkManager question

by icanwin (Acolyte)
on Mar 13, 2008 at 22:16 UTC ( #674084=perlquestion: print w/ replies, xml ) Need Help??
icanwin has asked for the wisdom of the Perl Monks concerning the following question:

Hi all

I'm currently using Parallel::ForkManager to perfom parallel operations. When I create a new child using the start method, I need to send the generated pid to the child process, however I cant do it (I know the start method returns the pid but this pid is not visible in the child process).

So, how can I know the pid in the child process?

And finally, How can I kill a child process? Sometimes in the wait_all_children method I get stuck beacuse the parent waits for a child that never ends. I need something to kill a child process if it runs more than 5m without finishing.

Thanks a lot.

Comment on Parallel::ForkManager question
Re: Parallel::ForkManager question
by ikegami (Pope) on Mar 13, 2008 at 22:20 UTC

    You want to know the child's PID in the child? $$.
    You want to know the parent's PID in the child? Just store $$ into a variable (say $ppid) before the loop.
    You want to know the child's PID in the parent? Use the snippet below.

    for (...) { my $pid = $pm->start; if ($pid) { # We're in the parent. ...[ do something with $pid ]... next; } # We're in the child. ... }

    Update: Added third question and answer.

Re: Parallel::ForkManager question
by ctilmes (Priest) on Mar 13, 2008 at 22:23 UTC
    Your PID is $$.

    You can kill a process with 'kill <signal>, <pid>', e.g. "kill 9 => 2713" (or "use Config; kill KILL => 2713;")

Re: Parallel::ForkManager question
by pc88mxer (Vicar) on Mar 13, 2008 at 22:29 UTC
    You can collect the pids of all the children created by Parallel::ForkManager thusly:
    my $parent_pid = $$; my @pids; my $pm = new Parallel::ForkManager($MAX_PROCESSES); foreach $data (@all_data) { my $pid = $pm->start; if ($pid) { push(@pids, $pid); next; } # child executes here # ... and pid of parent is in $parent_pid $pm->finish; # child exits here } kill $signal, @pids; # signal children
    This code also incorporates ikegami's comment about how the child can get the parent's pid.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://674084]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2014-11-29 02:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (203 votes), past polls