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