PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/ext/IPC-Open3/lib/IPC/Open3.pm

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