Jim
Jim

Reputation: 19582

How can I get a value from a child process?

I have a script and at some part I fork some processes to do a task and the main process waits for all children to complete.
So far all ok.
Problem: I am interested to get the max time that each child process spend while working on what it had to do.
What I do now is just look at the logs where I print the times spend at each action the child process did and try to figure out more or less the times.
I know that the only way to get something back from a child process is via some sort of shared memory but I was wondering for this specific problem is there a "ready"/easy solution?
I mean in order to get the times back and the parent process prints them in a nice fashion in one place.
I thought there could be a better way than just checking all over the logs....

Update based on comments:
I am not interested in the times of the child processes i.e. which child took most time to finish. Each child process is working on X tasks. Each of the tasks takes at worse case Y secs to finish. I am looking to find the Y i.e. the most time it took for a child process to finish one of the X tasks

Upvotes: 3

Views: 175

Answers (1)

Sobrique
Sobrique

Reputation: 53508

The biggest limitation of fork() is that it doesn't do IPC as easily as threads. Aside from trapping when a process starts and exits, what you're doing otherwise has a whole segment of the perl documentation.

What I would suggest is that what you probably want is a pipe and connect it to the child.

Something like this (not tested yet, I'm on a Windows box!)

use strict;
use warnings;

use Parallel::ForkManager;

my $manager = Parallel::ForkManager -> new ( 5 ) ; 
pipe ( my $read_handle, my $write_handle );

for ( 1..10 ) {
    $manager -> start and next; 
    close ( $read_handle ); 
    print {$write_handle} "$$ - child says hello!\n";
    $manager -> finish; 
}
close ( $write_handle ); 

while ( <$read_handle> ) { print; }

$manager -> wait_all_children();

Upvotes: 1

Related Questions