1. Forks off multiple child processes (as few as 1, or as many as 1500)
2. Use pipes so all child processes communicate results periodically to the parent. (The child processes periodically (anywhere between 1 - 5 seconds) write some performance values as they go about doing their task)
3. Run a master loop in parent to poll all the reader pipes and (for now) print what is printed by the child processes. (Later I need to expand this to push all the data to a web application server as a JSON array. That is the easy part and not of concern at the moment)
(I read that using select is a better option than polling, but am unable to figure out how to use select in this context. A bonus thank you if you can help me with using select in the parent. One of the main hurdles for me is the fact that the child processes can run for quite sometime and having the parent wait until the child exits is impractical. The parent also needs to be reporting the values periodically.)
To begin with, I used a for loop to fork off child processes (after creating a pipe). Then use an infinite while loop to keep reading from the pipes. I know something is wrong, but need some guidance on it.
Here is the code:#!/usr/bin/perl use strict; use warnings; use IO::Handle; my @kids = (); my @readers; my @writers; my $pid; foreach my $i (1..3) { pipe $readers[$i], $writers[$i] or die "Unable to Create read/writ +e pipe for #$i\n"; $writers[$i]->autoflush(1); $pid = fork; unless (defined($pid)) { print "Unable to fork a child\n"; exit(1); } elsif ($pid) { # Parent push @kids, $pid; close($writers[$i]); next; } else { # Child print "Child Created: $$\n"; close($readers[$i]); $| = 1; my $report; foreach my $i (1..10) { $report = sprintf("%.2f", rand(100)); print $writers[$i],"[$$] $report\n"; sleep(2); } exit(0); } } my $rin; if ($pid) { print "Kids: @kids\n"; print "Readhing from Child handle\n"; while (1) { foreach my $i (0..$#kids) { if (<$readers[$i]>) { if (defined($_)) { print "[parent] $_\n"; } else { print "[parent] <Empty>\n"; } } else { print "Nothing to read\n"; } } sleep(1); } }
I know there are a few (unrelated to the problem) issues in the code, but in the interest of getting a working solution, I am ignoring them, on purpose.
In reply to Reading from Many Child Processes using Pipes by sved
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |