16.8. Controlling Input and Output of Another ProgramProblem
You want to both write to and read from another program. The SolutionUse the standard IPC::Open2 module: use IPC::Open2; open2(*README, *WRITEME, $program); print WRITEME "here's your input\n"; $output = <README>; close(WRITEME); close(README); Discussion
Wanting simultaneous read and write access to another program is very common, but surprisingly perilous. That's why open(DOUBLE_HANDLE, "| program args |") # WRONG The big problem here is buffering. Because you can't force the other program to unbuffer its output, you can't guarantee that your reads won't block. If you block trying to read at the same time the other process blocks waiting for you to send something, you've achieved the unholy state of deadlock. There you'll both stay, wedged, until someone kills your process or the machine reboots.
If you control the other process's buffering because you wrote the other program and know how it works, then
IPC::Open2 may be the module for you. The first two arguments to use IPC::Open2; use IO::Handle; ($reader, $writer) = (IO::Handle->new, IO::Handle->new); open2($reader, $writer, $program);
If you pass in objects, you must have created them (with
Alternatively, you can pass in arguments that look like You can specify the program either as a list (where the first element is the program name and the remaining elements are arguments to the program) or as a single string (which is passed to the shell as a command to start the program). If you also want control over the process's standard error, use the IPC::Open3 module and see the next recipe.
If an error occurs, eval { open2($readme, $writeme, @program_and_arguments); }; if ($@) { if ($@ =~ /^open2/) { warn "open2 failed: $!\n$@\n"; return; } die; # reraise unforeseen exception } See Also
The documentation for the IPC::Open2 and IPC::Open3 modules;
Recipe 10.12
; the
|
|