pipe

pipeREADHANDLE,WRITEHANDLE
Like the corresponding syscall, this function opens a pair of
connected pipes—see pipe(2). This call is usually
used right before a fork, after which
the pipe’s reader should close WRITEHANDLE,
and the writer close READHANDLE. (Otherwise,
the pipe won’t indicate EOF to the reader when the writer closes it.) If
you set up a loop of piped processes, deadlock can occur unless you are
remarkably careful. In addition, note that Perl’s pipes use standard I/O
buffering, so you may need to set $|
($OUTPUT_AUTOFLUSH) on your
WRITEHANDLE to flush after each output
operation, depending on the application—see select (output filehandle).
(As with open, if either
filehandle is undefined, it will be autovivified.)
Here’s a small example:
pipe(README, WRITEME);
unless ($pid = fork) { # child
defined($pid) || die "can't fork: $!";
close(README);
for $i (1..5) { print WRITEME "line $i\n" }
exit;
}
$SIG{CHLD} = sub { waitpid($pid, 0) };
close(WRITEME);
@strings = <README>;
close(README);
print "Got:\n", @strings;Notice how the writer closes the read end and the reader closes the write end. You can’t use one pipe for two-way communication. Either use two different pipes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access