Skip to Main Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced content levelIntermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

IPC::Open2

use IPC::Open2;local(*HIS_OUT, *HIS_IN);  # Create local handles if needed.
$childpid = open2(*HIS_OUT, *HIS_IN, $program, @args)
    or die "can't open pipe to $program: $!";
print HIS_IN "here's your input\n";
$his_output = <HIS_IN>;
close(HIS_OUT);
close(README);
waitpid($childpid, 0);

The IPC::Open2 module's one exported function, open2, starts up another program and provides both read and write access to that command. The first two arguments should be valid filehandles (or else empty variables into which autogenerated filehandles can be placed). The remaining arguments are the program plus its arguments, which if passed in separately will not be subject to shell interpolation. This module does not reap the child process after it exits. Except for short programs where it's acceptable to let the operating system take care of this, you need to do this yourself. This is normally as simple as calling waitpid $pid, 0 when you're done with that child process. Failure to do this can result in an accumulation of defunct ("zombie") processes.

In practice, this module doesn't work well with many programs because of the way buffering works in C's standard I/O library. If you control the source code to both programs, however, you can easily circumvent this restriction by flushing your output buffers more frequently than the default. If you don't, programs can be annoyingly miserly in their hoarding of output. Another potential pitfall is deadlock: if both processes are reading at the ...

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.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata