Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Perl fork childs with variables

by adiuva (Sexton)
on Mar 06, 2013 at 23:28 UTC ( #1022120=perlquestion: print w/ replies, xml ) Need Help??
adiuva has asked for the wisdom of the Perl Monks concerning the following question:

Dear Perl masters,
I actually feel kinda stupid asking this, but I couldn't find an appropriate answer on the web. Basically I need to fork 2 childs and from each child I need to call a subroutine with 2 parameters. But from what I've seen so far, it's somehow not possible. It should look like this:
fork child 1 -> $return1 = subroutine($param1, $param2) fork child 2 -> $return2 = subroutine($param3, $param4) wait for both childs to finish run other code with $return1 and $return2
Can't be that hard to do, right?

Thanks for any help in advance!
Stefan

Comment on Perl fork childs with variables
Download Code
Re: Perl fork childs with variables
by rjt (Deacon) on Mar 07, 2013 at 01:02 UTC

    Hello Stefan!

    The thing with a fork()'d model is that the operating system is creating two additional and separate processes. While they initially have (nearly) the same state as the parent, they are in fact separate, and any changes to memory (i.e., variables) in one will have no effect on the other processes, just as you would expect with any other distinct process.

    All is not lost: you will need to use some form of inter-process communication (IPC) to allow your processes to communicate their results to the parent. If you are in a POSIX environment (likely, if you are using fork()), you might have a look at IPC::SysV and IPC::Msg for a start, and do some searching on http://www.cpan.org for other IPC modules best suited to what you need to do.

    Finally, is there a special reason you actually need a fork()'d model in the first place? Can you use threads instead? Perl's threads implementation makes shared variables and semaphores between threads very easy.

Re: Perl fork childs with variables
by ikegami (Pope) on Mar 07, 2013 at 01:04 UTC
    use forks; my $fork1 = async { return subroutine($param1, $param2); }; my $fork2 = async { return subroutine($param3, $param4); }; my $return1 = $fork1->join(); my $return2 = $fork2->join();

    But there's no need for two forks.

    use forks; my $fork1 = async { return subroutine($param1, $param2); }; my $return2 = subroutine($param3, $param4); my $return1 = $fork1->join();

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (17)
As of 2014-08-27 16:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (244 votes), past polls