8 IPC::Open2, open2 - open a process for both reading and writing
13 $pid = open2(\*RDR, \*WTR, 'some cmd and args');
15 $pid = open2(\*RDR, \*WTR, 'some', 'cmd', 'and', 'args');
19 The open2() function spawns the given $cmd and connects $rdr for
20 reading and $wtr for writing. It's what you think should work
23 open(HANDLE, "|cmd args");
25 open2() returns the process ID of the child process. It doesn't return on
26 failure: it just raises an exception matching C</^open2:/>.
30 It will not create these file handles for you. You have to do this yourself.
31 So don't pass it empty variables expecting them to get filled in for you.
33 Additionally, this is very dangerous as you may block forever.
34 It assumes it's going to talk to something like B<bc>, both writing to
35 it and reading from it. This is presumably safe because you "know"
36 that commands like B<bc> will read a line at a time and output a line at
37 a time. Programs like B<sort> that read their entire input stream first,
38 however, are quite apt to cause deadlock.
40 The big problem with this approach is that if you don't have control
41 over source code being run in the the child process, you can't control what it does
42 with pipe buffering. Thus you can't just open a pipe to C<cat -v> and continually
43 read and write a line from it.
47 See L<open3> for an alternative that handles STDERR as well.
54 # &open2: tom christiansen, <tchrist@convex.com>
56 # usage: $pid = open2('rdr', 'wtr', 'some cmd and args');
57 # or $pid = open2('rdr', 'wtr', 'some', 'cmd', 'and', 'args');
59 # spawn the given $cmd and connect $rdr for
60 # reading and $wtr for writing. return pid
61 # of child, or 0 on failure.
63 # WARNING: this is dangerous, as you may block forever
64 # unless you are very careful.
66 # $wtr is left unbuffered.
70 # pipe or fork or exec fails
72 $fh = 'FHOPEN000'; # package static in case called more than once
76 local($dad_rdr, $dad_wtr, @cmd) = @_;
78 $dad_rdr ne '' || croak "open2: rdr should not be null";
79 $dad_wtr ne '' || croak "open2: wtr should not be null";
81 # force unqualified filehandles into callers' package
82 local($package) = caller;
83 $dad_rdr =~ s/^([^']+$)/$package'$1/ unless ref $dad_rdr;
84 $dad_wtr =~ s/^([^']+$)/$package'$1/ unless ref $dad_wtr;
86 local($kid_rdr) = ++$fh;
87 local($kid_wtr) = ++$fh;
89 pipe($dad_rdr, $kid_wtr) || croak "open2: pipe 1 failed: $!";
90 pipe($kid_rdr, $dad_wtr) || croak "open2: pipe 2 failed: $!";
92 if (($kidpid = fork) < 0) {
93 croak "open2: fork failed: $!";
94 } elsif ($kidpid == 0) {
95 close $dad_rdr; close $dad_wtr;
96 open(STDIN, "<&$kid_rdr");
97 open(STDOUT, ">&$kid_wtr");
98 warn "execing @cmd\n" if $debug;
100 or croak "open2: exec of @cmd failed";
102 close $kid_rdr; close $kid_wtr;
103 select((select($dad_wtr), $| = 1)[0]); # unbuffer pipe
106 1; # so require is happy