pipe#
Open a pair of connected filehandles — one for reading, one for writing.
pipe wraps the pipe(2) system call. It creates an unnamed,
unidirectional byte channel in the kernel and hands you two
filehandles: READHANDLE, from which bytes can be read, and
WRITEHANDLE, into which bytes can be written. Anything written to
WRITEHANDLE becomes available on READHANDLE in the same order.
The classic use is communication between a parent process and a
child produced by fork: one side writes, the other reads.
Synopsis#
pipe READHANDLE, WRITEHANDLE
What you get back#
True on success, false on failure (with $! set to the reason —
typically EMFILE or ENFILE when the process or system file-table
is full). Both handles are created as side effects on the arguments;
there is no “pipe object” return value.
On success you now hold two open file descriptors. Every
descriptor you create is a descriptor you must close —
especially the end each process does not use after a
fork (see Edge cases).
Global state it touches#
$!— set on failure to theerrnofrom the underlyingpipe(2)call.$|— autoflush on the write-side handle.printbuffers through PerlIO, so without autoflush the reader may see nothing until the writer exits or the buffer fills. Set$|on the write handle (typically viaselect) before writing, or your protocol will deadlock.$^F— the maximum system filehandle. New descriptors withfilenogreater than$^F(default2, i.e. aboveSTDERR) have the close-on-exec flag set automatically, so they do not leak into programs started byexec. Lower$^Fto keep the pipe open acrossexec; raise it, or dup onto a low-numbered fd, to force inheritance.
Examples#
A parent writes a line; a forked child reads it:
pipe my $reader, my $writer or die "pipe: $!";
my $pid = fork // die "fork: $!";
if ($pid == 0) {
# child: reads only
close $writer;
my $line = <$reader>;
print "child saw: $line";
close $reader;
exit 0;
}
# parent: writes only
close $reader;
$writer->autoflush(1);
print $writer "hello from parent\n";
close $writer;
waitpid $pid, 0;
The child reports the other direction — a child produces data, the parent consumes it:
pipe my $reader, my $writer or die "pipe: $!";
my $pid = fork // die "fork: $!";
if ($pid == 0) {
close $reader;
$writer->autoflush(1);
print $writer "$_\n" for 1 .. 5;
close $writer;
exit 0;
}
close $writer;
while (my $line = <$reader>) {
print "got: $line";
}
close $reader;
waitpid $pid, 0;
Autoflush from the selected-handle side, for code that predates
IO::Handle method calls:
pipe my $reader, my $writer or die "pipe: $!";
my $old = select $writer; $| = 1; select $old;
For most uses, open with a pipe mode is simpler — it forks,
pipes, and execs for you:
open my $fh, '|-', 'gzip', '-c' or die $!; # write to gzip's stdin
print $fh "data\n";
close $fh;
open my $fh, '-|', 'ls', '-l' or die $!; # read from ls's stdout
while (my $line = <$fh>) { print $line }
close $fh;
Reach for bare pipe when you need both directions, need to retain
the unexec’d child, or are building something open’s two
pipe-forms do not cover — then IPC::Open2 /
IPC::Open3 wrap the pipe + fork +
exec dance for you.
Edge cases#
Close the end you do not use. After
fork, both processes hold both descriptors. The reader must close the write end, and the writer must close the read end. Skip this and you get the classic pipe bug: the reader’s<$reader>never returns EOF, because the kernel still sees a writer open (the reader’s own, idle, copy of$writer). The program hangs.Writing to a reader-less pipe raises
SIGPIPE. Once every copy of the read end is closed, the nextprinton the write side deliversSIGPIPE, whose default action is to kill the process. Install$SIG{PIPE} = 'IGNORE'(or a handler) to turn it into a normal write failure with$!set toEPIPE, which you can then check.Deadlock in pipe loops. Two processes each writing to the other through pipes will block forever if both write buffers fill before either process reads. Kernel pipe buffers are small (typically 64 KiB). Drain one side, use non-blocking I/O, or use
select/IO::Selectto multiplex.Buffering hides writes. Without
$|(or$writer->autoflush(1)) on the write side, data sits in PerlIO’s buffer until the buffer fills or the handle is closed. A reader blocked on<$reader>will wait — often indefinitely — for data that has already been “written” from the writer’s point of view.Unidirectional only.
pipeproduces a one-way channel: write toWRITEHANDLE, read fromREADHANDLE, not the reverse. For bidirectional communication usesocketpairor two pipes.Binary data. The handles returned by
pipestart in the default PerlIO layer stack. If you are moving raw bytes across the pipe, applybinmodeto both ends; otherwise CRLF or encoding layers inherited from the process defaults can rewrite your data.Close-on-exec and
fileno. On systems withFD_CLOEXEC, any new descriptor whosefilenoexceeds$^Fis created with the close-on-exec flag set. Pipe descriptors typically land well above2, so by default they do not surviveexec— which is normally what you want. Lower$^Fbefore callingpipeif you intend to pass the descriptors to anexec’d program.
Differences from upstream#
Fully compatible with upstream Perl 5.42.
See also#
fork— the other half of the pipe idiom;pipeis almost always called just before aforkopen— the'|-'and'-|'modes fork, pipe, andexeca child in one call; prefer them when you need exactly one direction to one external commandclose— closing the unused end in each process is mandatory, not optionalread— byte-oriented reads fromREADHANDLEwhen the line-oriented<$fh>form is the wrong shapeprint— the normal way to push data intoWRITEHANDLE; remember$|fileno— recover the underlying file descriptor, e.g. to hand toselect/IO::Selector to a lower-level system call