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.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);
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 same time, and no one is writing, then your program will hang. See Chapter 16, "Interprocess Communication" for more discussion.
Copyright © 2002 O'Reilly & Associates. All rights reserved.