A co-worker of mine is trying to write a simple unidirectional named pipe script where the parent process will assign tasks to several child processes. The idea was to have each child read only one line from the pipe, which he tells me can be done in C. But apparently in Perl the first child to connect is reading the entire buffer.
Since he's out today I thought I would try my very inexperienced hand at this. The closest I could get is below, which is based on an exmaple in Network Programming with Perl. Since I'm not really familair with this type of programming I used pipe() instead of named pipes.
To reitierate, the question is is there a way to have each child process actually read just one line from the pipe? Any pointers (and other terrible C puns) are appreciated!!
#!/usr/local/bin/perl
use strict;
use warnings;
sub child {
my( $child ) = @_;
if( fork == 0 ) { # Child
close WRITER;
select STDOUT; $| = 1;
select READER; $| = 1;
while( 1 ) {
my $line = <READER>;
print STDOUT "$child: $line";
sleep 1;
}
}
return;
}
pipe( READER, WRITER ) or die "Can't open pipe: $!";
# Create children
child( 'a' ); child( 'b' );
child( 'c' ); child( 'd' );
child( 'e' );
# Parent
close READER;
select WRITER; $| = 1;
my $str = "";
foreach ( 0..50 ) { $str .= "$_\n"; }
while( 1 ) { print WRITER $str; }
Update: Put the sleep 1 in and merged some of the child() lines.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.