Subject: [PATCH] Suppress diag msg from IPC::Cmd
[p5sagit/p5-mst-13.2.git] / lib / IPC / Open3.pm
CommitLineData
a0d0e21e 1package IPC::Open3;
7e1af8bc 2
3use strict;
4no strict 'refs'; # because users pass me bareword filehandles
2675ae2b 5our ($VERSION, @ISA, @EXPORT);
7e1af8bc 6
a0d0e21e 7require Exporter;
7e1af8bc 8
a0d0e21e 9use Carp;
8b3e92c6 10use Symbol qw(gensym qualify);
7e1af8bc 11
ae8d64f5 12$VERSION = 1.03;
7e1af8bc 13@ISA = qw(Exporter);
14@EXPORT = qw(open3);
a0d0e21e 15
f06db76b 16=head1 NAME
17
18IPC::Open3, open3 - open a process for reading, writing, and error handling
19
20=head1 SYNOPSIS
21
3ce239a0 22 $pid = open3(\*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR,
f06db76b 23 'some cmd and args', 'optarg', ...);
24
2675ae2b 25 my($wtr, $rdr, $err);
26 $pid = open3($wtr, $rdr, $err,
27 'some cmd and args', 'optarg', ...);
28
b2080196 29 waitpid( $pid, 0 );
30 my $child_exit_status = $? >> 8;
31
f06db76b 32=head1 DESCRIPTION
33
34Extremely similar to open2(), open3() spawns the given $cmd and
3ce239a0 35connects CHLD_OUT for reading from the child, CHLD_IN for writing to
36the child, and CHLD_ERR for errors. If CHLD_ERR is false, or the
37same file descriptor as CHLD_OUT, then STDOUT and STDERR of the child
38are on the same filehandle. The CHLD_IN will have autoflush turned
39on.
40
41If CHLD_IN begins with C<< <& >>, then CHLD_IN will be closed in the
42parent, and the child will read from it directly. If CHLD_OUT or
43CHLD_ERR begins with C<< >& >>, then the child will send output
44directly to that filehandle. In both cases, there will be a dup(2)
45instead of a pipe(2) made.
f06db76b 46
2675ae2b 47If either reader or writer is the null string, this will be replaced
48by an autogenerated filehandle. If so, you must pass a valid lvalue
49in the parameter slot so it can be overwritten in the caller, or
50an exception will be raised.
cb1a09d0 51
036b4402 52The filehandles may also be integers, in which case they are understood
53as file descriptors.
54
7e1af8bc 55open3() returns the process ID of the child process. It doesn't return on
2675ae2b 56failure: it just raises an exception matching C</^open3:/>. However,
eee4b3e7 57C<exec> failures in the child (such as no such file or permission denied),
58are just reported to CHLD_ERR, as it is not possible to trap them.
59
60If the child process dies for any reason, the next write to CHLD_IN is
61likely to generate a SIGPIPE in the parent, which is fatal by default.
62So you may wish to handle this signal.
f06db76b 63
a2a63531 64Note if you specify C<-> as the command, in an analogous fashion to
65C<open(FOO, "-|")> the child process will just be the forked Perl
66process rather than an external command. This feature isn't yet
67supported on Win32 platforms.
68
4375e838 69open3() does not wait for and reap the child process after it exits.
227e8dd4 70Except for short programs where it's acceptable to let the operating system
71take care of this, you need to do this yourself. This is normally as
72simple as calling C<waitpid $pid, 0> when you're done with the process.
73Failing to do this can result in an accumulation of defunct or "zombie"
74processes. See L<perlfunc/waitpid> for more information.
75
2675ae2b 76If you try to read from the child's stdout writer and their stderr
77writer, you'll have problems with blocking, which means you'll want
78to use select() or the IO::Select, which means you'd best use
79sysread() instead of readline() for normal stuff.
80
81This is very dangerous, as you may block forever. It assumes it's
82going to talk to something like B<bc>, both writing to it and reading
83from it. This is presumably safe because you "know" that commands
84like B<bc> will read a line at a time and output a line at a time.
85Programs like B<sort> that read their entire input stream first,
7e1af8bc 86however, are quite apt to cause deadlock.
87
88The big problem with this approach is that if you don't have control
7a2e2cd6 89over source code being run in the child process, you can't control
7e1af8bc 90what it does with pipe buffering. Thus you can't just open a pipe to
91C<cat -v> and continually read and write a line from it.
92
eee4b3e7 93=head1 See Also
94
95=over 4
96
97=item L<IPC::Open2>
98
99Like Open3 but without STDERR catpure.
100
101=item L<IPC::Run>
102
103This is a CPAN module that has better error handling and more facilities
104than Open3.
105
106=back
107
2675ae2b 108=head1 WARNING
109
110The order of arguments differs from that of open2().
111
7e1af8bc 112=cut
a0d0e21e 113
114# &open3: Marc Horowitz <marc@mit.edu>
115# derived mostly from &open2 by tom christiansen, <tchrist@convex.com>
4633a7c4 116# fixed for 5.001 by Ulrich Kunitz <kunitz@mai-koeln.com>
f55ee38a 117# ported to Win32 by Ron Schmidt, Merrill Lynch almost ended my career
2675ae2b 118# fixed for autovivving FHs, tchrist again
6662521e 119# allow fd numbers to be used, by Frank Tobin
a2a63531 120# allow '-' as command (c.f. open "-|"), by Adam Spiers <perl@adamspiers.org>
a0d0e21e 121#
122# $Id: open3.pl,v 1.1 1993/11/23 06:26:15 marc Exp $
123#
124# usage: $pid = open3('wtr', 'rdr', 'err' 'some cmd and args', 'optarg', ...);
125#
126# spawn the given $cmd and connect rdr for
127# reading, wtr for writing, and err for errors.
128# if err is '', or the same as rdr, then stdout and
129# stderr of the child are on the same fh. returns pid
7e1af8bc 130# of child (or dies on failure).
a0d0e21e 131
132
4633a7c4 133# if wtr begins with '<&', then wtr will be closed in the parent, and
a0d0e21e 134# the child will read from it directly. if rdr or err begins with
135# '>&', then the child will send output directly to that fd. In both
136# cases, there will be a dup() instead of a pipe() made.
137
138
139# WARNING: this is dangerous, as you may block forever
140# unless you are very careful.
141#
142# $wtr is left unbuffered.
143#
144# abort program if
145# rdr or wtr are null
7e1af8bc 146# a system call fails
a0d0e21e 147
2675ae2b 148our $Me = 'open3 (bug)'; # you should never see this, it's always localized
a0d0e21e 149
7e1af8bc 150# Fatal.pm needs to be fixed WRT prototypes.
151
152sub xfork {
153 my $pid = fork;
154 defined $pid or croak "$Me: fork failed: $!";
155 return $pid;
156}
157
158sub xpipe {
159 pipe $_[0], $_[1] or croak "$Me: pipe($_[0], $_[1]) failed: $!";
160}
161
162# I tried using a * prototype character for the filehandle but it still
163# disallows a bearword while compiling under strict subs.
a0d0e21e 164
7e1af8bc 165sub xopen {
166 open $_[0], $_[1] or croak "$Me: open($_[0], $_[1]) failed: $!";
167}
168
169sub xclose {
170 close $_[0] or croak "$Me: close($_[0]) failed: $!";
171}
172
036b4402 173sub fh_is_fd {
174 return $_[0] =~ /\A=?(\d+)\z/;
6662521e 175}
176
036b4402 177sub xfileno {
178 return $1 if $_[0] =~ /\A=?(\d+)\z/; # deal with fh just being an fd
179 return fileno $_[0];
6662521e 180}
181
f55ee38a 182my $do_spawn = $^O eq 'os2' || $^O eq 'MSWin32';
a24d8dfd 183
7e1af8bc 184sub _open3 {
185 local $Me = shift;
186 my($package, $dad_wtr, $dad_rdr, $dad_err, @cmd) = @_;
187 my($dup_wtr, $dup_rdr, $dup_err, $kidpid);
188
eee4b3e7 189 if (@cmd > 1 and $cmd[0] eq '-') {
190 croak "Arguments don't make sense when the command is '-'"
191 }
192
2675ae2b 193 # simulate autovivification of filehandles because
194 # it's too ugly to use @_ throughout to make perl do it for us
195 # tchrist 5-Mar-00
196
197 unless (eval {
198 $dad_wtr = $_[1] = gensym unless defined $dad_wtr && length $dad_wtr;
199 $dad_rdr = $_[2] = gensym unless defined $dad_rdr && length $dad_rdr;
200 1; })
201 {
202 # must strip crud for croak to add back, or looks ugly
203 $@ =~ s/(?<=value attempted) at .*//s;
204 croak "$Me: $@";
205 }
206
207 $dad_err ||= $dad_rdr;
a0d0e21e 208
4633a7c4 209 $dup_wtr = ($dad_wtr =~ s/^[<>]&//);
210 $dup_rdr = ($dad_rdr =~ s/^[<>]&//);
211 $dup_err = ($dad_err =~ s/^[<>]&//);
a0d0e21e 212
2675ae2b 213 # force unqualified filehandles into caller's package
6662521e 214 $dad_wtr = qualify $dad_wtr, $package unless fh_is_fd($dad_wtr);
215 $dad_rdr = qualify $dad_rdr, $package unless fh_is_fd($dad_rdr);
216 $dad_err = qualify $dad_err, $package unless fh_is_fd($dad_err);
7e1af8bc 217
8b3e92c6 218 my $kid_rdr = gensym;
219 my $kid_wtr = gensym;
220 my $kid_err = gensym;
7e1af8bc 221
222 xpipe $kid_rdr, $dad_wtr if !$dup_wtr;
223 xpipe $dad_rdr, $kid_wtr if !$dup_rdr;
224 xpipe $dad_err, $kid_err if !$dup_err && $dad_err ne $dad_rdr;
225
a24d8dfd 226 $kidpid = $do_spawn ? -1 : xfork;
227 if ($kidpid == 0) { # Kid
c6770908 228 # A tie in the parent should not be allowed to cause problems.
229 untie *STDIN;
230 untie *STDOUT;
7e1af8bc 231 # If she wants to dup the kid's stderr onto her stdout I need to
232 # save a copy of her stdout before I put something else there.
233 if ($dad_rdr ne $dad_err && $dup_err
6662521e 234 && xfileno($dad_err) == fileno(STDOUT)) {
8b3e92c6 235 my $tmp = gensym;
7e1af8bc 236 xopen($tmp, ">&$dad_err");
237 $dad_err = $tmp;
238 }
a0d0e21e 239
a0d0e21e 240 if ($dup_wtr) {
6662521e 241 xopen \*STDIN, "<&$dad_wtr" if fileno(STDIN) != xfileno($dad_wtr);
a0d0e21e 242 } else {
8ebc5c01 243 xclose $dad_wtr;
8b3e92c6 244 xopen \*STDIN, "<&=" . fileno $kid_rdr;
a0d0e21e 245 }
246 if ($dup_rdr) {
6662521e 247 xopen \*STDOUT, ">&$dad_rdr" if fileno(STDOUT) != xfileno($dad_rdr);
a0d0e21e 248 } else {
8ebc5c01 249 xclose $dad_rdr;
8b3e92c6 250 xopen \*STDOUT, ">&=" . fileno $kid_wtr;
a0d0e21e 251 }
252 if ($dad_rdr ne $dad_err) {
253 if ($dup_err) {
8b3e92c6 254 # I have to use a fileno here because in this one case
255 # I'm doing a dup but the filehandle might be a reference
256 # (from the special case above).
6662521e 257 xopen \*STDERR, ">&" . xfileno($dad_err)
258 if fileno(STDERR) != xfileno($dad_err);
a0d0e21e 259 } else {
8ebc5c01 260 xclose $dad_err;
8b3e92c6 261 xopen \*STDERR, ">&=" . fileno $kid_err;
a0d0e21e 262 }
263 } else {
8ebc5c01 264 xopen \*STDERR, ">&STDOUT" if fileno(STDERR) != fileno(STDOUT);
a0d0e21e 265 }
eee4b3e7 266 return 0 if ($cmd[0] eq '-');
a0d0e21e 267 local($")=(" ");
64ab78e5 268 exec @cmd or do {
269 carp "$Me: exec of @cmd failed";
270 eval { require POSIX; POSIX::_exit(255); };
271 exit 255;
272 };
a24d8dfd 273 } elsif ($do_spawn) {
274 # All the bookkeeping of coincidence between handles is
275 # handled in spawn_with_handles.
276
277 my @close;
278 if ($dup_wtr) {
8b3e92c6 279 $kid_rdr = \*{$dad_wtr};
280 push @close, $kid_rdr;
a24d8dfd 281 } else {
8b3e92c6 282 push @close, \*{$dad_wtr}, $kid_rdr;
a24d8dfd 283 }
284 if ($dup_rdr) {
8b3e92c6 285 $kid_wtr = \*{$dad_rdr};
286 push @close, $kid_wtr;
a24d8dfd 287 } else {
8b3e92c6 288 push @close, \*{$dad_rdr}, $kid_wtr;
a24d8dfd 289 }
290 if ($dad_rdr ne $dad_err) {
291 if ($dup_err) {
8b3e92c6 292 $kid_err = \*{$dad_err};
293 push @close, $kid_err;
a24d8dfd 294 } else {
8b3e92c6 295 push @close, \*{$dad_err}, $kid_err;
a24d8dfd 296 }
297 } else {
298 $kid_err = $kid_wtr;
299 }
300 require IO::Pipe;
301 $kidpid = eval {
302 spawn_with_handles( [ { mode => 'r',
8b3e92c6 303 open_as => $kid_rdr,
a24d8dfd 304 handle => \*STDIN },
305 { mode => 'w',
8b3e92c6 306 open_as => $kid_wtr,
a24d8dfd 307 handle => \*STDOUT },
308 { mode => 'w',
8b3e92c6 309 open_as => $kid_err,
a24d8dfd 310 handle => \*STDERR },
311 ], \@close, @cmd);
312 };
ad973f30 313 die "$Me: $@" if $@;
a0d0e21e 314 }
315
7e1af8bc 316 xclose $kid_rdr if !$dup_wtr;
317 xclose $kid_wtr if !$dup_rdr;
318 xclose $kid_err if !$dup_err && $dad_rdr ne $dad_err;
319 # If the write handle is a dup give it away entirely, close my copy
320 # of it.
321 xclose $dad_wtr if $dup_wtr;
a0d0e21e 322
323 select((select($dad_wtr), $| = 1)[0]); # unbuffer pipe
324 $kidpid;
325}
7e1af8bc 326
327sub open3 {
a24d8dfd 328 if (@_ < 4) {
329 local $" = ', ';
330 croak "open3(@_): not enough arguments";
331 }
7e1af8bc 332 return _open3 'open3', scalar caller, @_
333}
a0d0e21e 334
a24d8dfd 335sub spawn_with_handles {
336 my $fds = shift; # Fields: handle, mode, open_as
337 my $close_in_child = shift;
338 my ($fd, $pid, @saved_fh, $saved, %saved, @errs);
339 require Fcntl;
340
341 foreach $fd (@$fds) {
342 $fd->{tmp_copy} = IO::Handle->new_from_fd($fd->{handle}, $fd->{mode});
343 $saved{fileno $fd->{handle}} = $fd->{tmp_copy};
344 }
345 foreach $fd (@$fds) {
346 bless $fd->{handle}, 'IO::Handle'
347 unless eval { $fd->{handle}->isa('IO::Handle') } ;
348 # If some of handles to redirect-to coincide with handles to
349 # redirect, we need to use saved variants:
350 $fd->{handle}->fdopen($saved{fileno $fd->{open_as}} || $fd->{open_as},
351 $fd->{mode});
352 }
f55ee38a 353 unless ($^O eq 'MSWin32') {
354 # Stderr may be redirected below, so we save the err text:
355 foreach $fd (@$close_in_child) {
356 fcntl($fd, Fcntl::F_SETFD(), 1) or push @errs, "fcntl $fd: $!"
357 unless $saved{fileno $fd}; # Do not close what we redirect!
358 }
a24d8dfd 359 }
360
361 unless (@errs) {
362 $pid = eval { system 1, @_ }; # 1 == P_NOWAIT
363 push @errs, "IO::Pipe: Can't spawn-NOWAIT: $!" if !$pid || $pid < 0;
364 }
365
366 foreach $fd (@$fds) {
367 $fd->{handle}->fdopen($fd->{tmp_copy}, $fd->{mode});
368 $fd->{tmp_copy}->close or croak "Can't close: $!";
369 }
370 croak join "\n", @errs if @errs;
371 return $pid;
372}
373
3741; # so require is happy