Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm using forks for the first time and I need to figure out how to save the results of the child process. I've written the following code. When I call the script, sometimes it runs fine, sometimes I lots of error messages. Obviously the child process doesn't finish, because I have to kill left-over processes. I've also tried a lot of other packages, but until now this is the best functioning code I could get. Can someone help?
#!/usr/bin/perl use forks; use forks::shared; use strict; use warnings; my $num = "10"; my @results = (); share(@results); my @children = (); for my $i (0..$num-1) { my $pid = fork(); if ($pid) { # Parent push @children, $pid; } elsif ($pid == 0) { # Child my $result = "abc"; # Later to be replaced with the # actual thing to be computed $results[$i] = $result; sleep 3; exit(0); } } foreach (@children) { waitpid($_, 0); } for (my $r=0 ; $r<@results; $r++) { print $r . "\t" . $results[$r] . "\n"; }

Replies are listed 'Best First'.
Re: Forks and IPC
by BrowserUk (Patriarch) on May 31, 2010 at 20:26 UTC

    If you are going to use forks & forks::shared, then you should use the functions and methods exported by those modules. fork is not one of them. Ie. You should read their documentation.

    threads & threads::shared do effectively the same thing as those two modules, but do it efficiently.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Forks and IPC
by JavaFan (Canon) on May 31, 2010 at 20:09 UTC
    When forking, parent and child do not share any memory - the child is a copy of the parent. You cannot pass information back to the parent by just modifying variables. If you want to do this using variables, you may want to explore the world of threads. Otherwise, with forks, you're better off using pipes - then you can pass any (serialized) data you want.

    You may want to read the perlipc manual page.

Re: Forks and IPC
by almut (Canon) on May 31, 2010 at 20:12 UTC

    If you want to use forks / forks::shared, you're normally supposed to use the threads API (which it emulates), instead of using the regular fork (well, there is support for fork in combination with threads->isthread, but it's special purpose).  See the docs for details/examples.