4 use vars qw($VERSION @ISA @EXPORT);
15 IPC::Open2, open2 - open a process for both reading and writing
20 $pid = open2(\*RDR, \*WTR, 'some cmd and args');
22 $pid = open2(\*RDR, \*WTR, 'some', 'cmd', 'and', 'args');
26 The open2() function spawns the given $cmd and connects $rdr for
27 reading and $wtr for writing. It's what you think should work
30 open(HANDLE, "|cmd args|");
32 If $rdr is a string (that is, a bareword filehandle rather than a glob
33 or a reference) and it begins with ">&", then the child will send output
34 directly to that file handle. If $wtr is a string that begins with
35 "<&", then WTR will be closed in the parent, and the child will read
36 from it directly. In both cases, there will be a dup(2) instead of a
39 open2() returns the process ID of the child process. It doesn't return on
40 failure: it just raises an exception matching C</^open2:/>.
44 It will not create these file handles for you. You have to do this yourself.
45 So don't pass it empty variables expecting them to get filled in for you.
47 Additionally, this is very dangerous as you may block forever.
48 It assumes it's going to talk to something like B<bc>, both writing to
49 it and reading from it. This is presumably safe because you "know"
50 that commands like B<bc> will read a line at a time and output a line at
51 a time. Programs like B<sort> that read their entire input stream first,
52 however, are quite apt to cause deadlock.
54 The big problem with this approach is that if you don't have control
55 over source code being run in the the child process, you can't control what it does
56 with pipe buffering. Thus you can't just open a pipe to C<cat -v> and continually
57 read and write a line from it.
61 See L<IPC::Open3> for an alternative that handles STDERR as well. This
62 function is really just a wrapper around open3().
66 # &open2: tom christiansen, <tchrist@convex.com>
68 # usage: $pid = open2('rdr', 'wtr', 'some cmd and args');
69 # or $pid = open2('rdr', 'wtr', 'some', 'cmd', 'and', 'args');
71 # spawn the given $cmd and connect $rdr for
72 # reading and $wtr for writing. return pid
73 # of child, or 0 on failure.
75 # WARNING: this is dangerous, as you may block forever
76 # unless you are very careful.
78 # $wtr is left unbuffered.
87 my ($read, $write, @cmd) = @_;
88 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
89 return IPC::Open3::_open3('open2', scalar caller,
90 $write, $read, '>&STDERR', @cmd);