Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

291 lines
8.5 KiB

  1. package IPC::Open3;
  2. use strict;
  3. no strict 'refs'; # because users pass me bareword filehandles
  4. use vars qw($VERSION @ISA @EXPORT $Me);
  5. require 5.001;
  6. require Exporter;
  7. use Carp;
  8. use Symbol qw(gensym qualify);
  9. $VERSION = 1.0103;
  10. @ISA = qw(Exporter);
  11. @EXPORT = qw(open3);
  12. =head1 NAME
  13. IPC::Open3, open3 - open a process for reading, writing, and error handling
  14. =head1 SYNOPSIS
  15. $pid = open3(\*WTRFH, \*RDRFH, \*ERRFH,
  16. 'some cmd and args', 'optarg', ...);
  17. =head1 DESCRIPTION
  18. Extremely similar to open2(), open3() spawns the given $cmd and
  19. connects RDRFH for reading, WTRFH for writing, and ERRFH for errors. If
  20. ERRFH is '', or the same as RDRFH, then STDOUT and STDERR of the child are
  21. on the same file handle. The WTRFH will have autoflush turned on.
  22. If WTRFH begins with "E<lt>&", then WTRFH will be closed in the parent, and
  23. the child will read from it directly. If RDRFH or ERRFH begins with
  24. "E<gt>&", then the child will send output directly to that file handle.
  25. In both cases, there will be a dup(2) instead of a pipe(2) made.
  26. If you try to read from the child's stdout writer and their stderr
  27. writer, you'll have problems with blocking, which means you'll
  28. want to use select(), which means you'll have to use sysread() instead
  29. of normal stuff.
  30. open3() returns the process ID of the child process. It doesn't return on
  31. failure: it just raises an exception matching C</^open3:/>.
  32. =head1 WARNING
  33. It will not create these file handles for you. You have to do this
  34. yourself. So don't pass it empty variables expecting them to get filled
  35. in for you.
  36. Additionally, this is very dangerous as you may block forever. It
  37. assumes it's going to talk to something like B<bc>, both writing to it
  38. and reading from it. This is presumably safe because you "know" that
  39. commands like B<bc> will read a line at a time and output a line at a
  40. time. Programs like B<sort> that read their entire input stream first,
  41. however, are quite apt to cause deadlock.
  42. The big problem with this approach is that if you don't have control
  43. over source code being run in the child process, you can't control
  44. what it does with pipe buffering. Thus you can't just open a pipe to
  45. C<cat -v> and continually read and write a line from it.
  46. =cut
  47. # &open3: Marc Horowitz <[email protected]>
  48. # derived mostly from &open2 by tom christiansen, <[email protected]>
  49. # fixed for 5.001 by Ulrich Kunitz <[email protected]>
  50. # ported to Win32 by Ron Schmidt, Merrill Lynch almost ended my career
  51. #
  52. # $Id: open3.pl,v 1.1 1993/11/23 06:26:15 marc Exp $
  53. #
  54. # usage: $pid = open3('wtr', 'rdr', 'err' 'some cmd and args', 'optarg', ...);
  55. #
  56. # spawn the given $cmd and connect rdr for
  57. # reading, wtr for writing, and err for errors.
  58. # if err is '', or the same as rdr, then stdout and
  59. # stderr of the child are on the same fh. returns pid
  60. # of child (or dies on failure).
  61. # if wtr begins with '<&', then wtr will be closed in the parent, and
  62. # the child will read from it directly. if rdr or err begins with
  63. # '>&', then the child will send output directly to that fd. In both
  64. # cases, there will be a dup() instead of a pipe() made.
  65. # WARNING: this is dangerous, as you may block forever
  66. # unless you are very careful.
  67. #
  68. # $wtr is left unbuffered.
  69. #
  70. # abort program if
  71. # rdr or wtr are null
  72. # a system call fails
  73. $Me = 'open3 (bug)'; # you should never see this, it's always localized
  74. # Fatal.pm needs to be fixed WRT prototypes.
  75. sub xfork {
  76. my $pid = fork;
  77. defined $pid or croak "$Me: fork failed: $!";
  78. return $pid;
  79. }
  80. sub xpipe {
  81. pipe $_[0], $_[1] or croak "$Me: pipe($_[0], $_[1]) failed: $!";
  82. }
  83. # I tried using a * prototype character for the filehandle but it still
  84. # disallows a bearword while compiling under strict subs.
  85. sub xopen {
  86. open $_[0], $_[1] or croak "$Me: open($_[0], $_[1]) failed: $!";
  87. }
  88. sub xclose {
  89. close $_[0] or croak "$Me: close($_[0]) failed: $!";
  90. }
  91. my $do_spawn = $^O eq 'os2' || $^O eq 'MSWin32';
  92. sub _open3 {
  93. local $Me = shift;
  94. my($package, $dad_wtr, $dad_rdr, $dad_err, @cmd) = @_;
  95. my($dup_wtr, $dup_rdr, $dup_err, $kidpid);
  96. $dad_wtr or croak "$Me: wtr should not be null";
  97. $dad_rdr or croak "$Me: rdr should not be null";
  98. $dad_err = $dad_rdr if ($dad_err eq '');
  99. $dup_wtr = ($dad_wtr =~ s/^[<>]&//);
  100. $dup_rdr = ($dad_rdr =~ s/^[<>]&//);
  101. $dup_err = ($dad_err =~ s/^[<>]&//);
  102. # force unqualified filehandles into callers' package
  103. $dad_wtr = qualify $dad_wtr, $package;
  104. $dad_rdr = qualify $dad_rdr, $package;
  105. $dad_err = qualify $dad_err, $package;
  106. my $kid_rdr = gensym;
  107. my $kid_wtr = gensym;
  108. my $kid_err = gensym;
  109. xpipe $kid_rdr, $dad_wtr if !$dup_wtr;
  110. xpipe $dad_rdr, $kid_wtr if !$dup_rdr;
  111. xpipe $dad_err, $kid_err if !$dup_err && $dad_err ne $dad_rdr;
  112. $kidpid = $do_spawn ? -1 : xfork;
  113. if ($kidpid == 0) { # Kid
  114. # If she wants to dup the kid's stderr onto her stdout I need to
  115. # save a copy of her stdout before I put something else there.
  116. if ($dad_rdr ne $dad_err && $dup_err
  117. && fileno($dad_err) == fileno(STDOUT)) {
  118. my $tmp = gensym;
  119. xopen($tmp, ">&$dad_err");
  120. $dad_err = $tmp;
  121. }
  122. if ($dup_wtr) {
  123. xopen \*STDIN, "<&$dad_wtr" if fileno(STDIN) != fileno($dad_wtr);
  124. } else {
  125. xclose $dad_wtr;
  126. xopen \*STDIN, "<&=" . fileno $kid_rdr;
  127. }
  128. if ($dup_rdr) {
  129. xopen \*STDOUT, ">&$dad_rdr" if fileno(STDOUT) != fileno($dad_rdr);
  130. } else {
  131. xclose $dad_rdr;
  132. xopen \*STDOUT, ">&=" . fileno $kid_wtr;
  133. }
  134. if ($dad_rdr ne $dad_err) {
  135. if ($dup_err) {
  136. # I have to use a fileno here because in this one case
  137. # I'm doing a dup but the filehandle might be a reference
  138. # (from the special case above).
  139. xopen \*STDERR, ">&" . fileno $dad_err
  140. if fileno(STDERR) != fileno($dad_err);
  141. } else {
  142. xclose $dad_err;
  143. xopen \*STDERR, ">&=" . fileno $kid_err;
  144. }
  145. } else {
  146. xopen \*STDERR, ">&STDOUT" if fileno(STDERR) != fileno(STDOUT);
  147. }
  148. local($")=(" ");
  149. exec @cmd
  150. or croak "$Me: exec of @cmd failed";
  151. } elsif ($do_spawn) {
  152. # All the bookkeeping of coincidence between handles is
  153. # handled in spawn_with_handles.
  154. my @close;
  155. if ($dup_wtr) {
  156. $kid_rdr = \*{$dad_wtr};
  157. push @close, $kid_rdr;
  158. } else {
  159. push @close, \*{$dad_wtr}, $kid_rdr;
  160. }
  161. if ($dup_rdr) {
  162. $kid_wtr = \*{$dad_rdr};
  163. push @close, $kid_wtr;
  164. } else {
  165. push @close, \*{$dad_rdr}, $kid_wtr;
  166. }
  167. if ($dad_rdr ne $dad_err) {
  168. if ($dup_err) {
  169. $kid_err = \*{$dad_err};
  170. push @close, $kid_err;
  171. } else {
  172. push @close, \*{$dad_err}, $kid_err;
  173. }
  174. } else {
  175. $kid_err = $kid_wtr;
  176. }
  177. require IO::Pipe;
  178. $kidpid = eval {
  179. spawn_with_handles( [ { mode => 'r',
  180. open_as => $kid_rdr,
  181. handle => \*STDIN },
  182. { mode => 'w',
  183. open_as => $kid_wtr,
  184. handle => \*STDOUT },
  185. { mode => 'w',
  186. open_as => $kid_err,
  187. handle => \*STDERR },
  188. ], \@close, @cmd);
  189. };
  190. die "$Me: $@" if $@;
  191. }
  192. xclose $kid_rdr if !$dup_wtr;
  193. xclose $kid_wtr if !$dup_rdr;
  194. xclose $kid_err if !$dup_err && $dad_rdr ne $dad_err;
  195. # If the write handle is a dup give it away entirely, close my copy
  196. # of it.
  197. xclose $dad_wtr if $dup_wtr;
  198. select((select($dad_wtr), $| = 1)[0]); # unbuffer pipe
  199. $kidpid;
  200. }
  201. sub open3 {
  202. if (@_ < 4) {
  203. local $" = ', ';
  204. croak "open3(@_): not enough arguments";
  205. }
  206. return _open3 'open3', scalar caller, @_
  207. }
  208. sub spawn_with_handles {
  209. my $fds = shift; # Fields: handle, mode, open_as
  210. my $close_in_child = shift;
  211. my ($fd, $pid, @saved_fh, $saved, %saved, @errs);
  212. require Fcntl;
  213. foreach $fd (@$fds) {
  214. $fd->{tmp_copy} = IO::Handle->new_from_fd($fd->{handle}, $fd->{mode});
  215. $saved{fileno $fd->{handle}} = $fd->{tmp_copy};
  216. }
  217. foreach $fd (@$fds) {
  218. bless $fd->{handle}, 'IO::Handle'
  219. unless eval { $fd->{handle}->isa('IO::Handle') } ;
  220. # If some of handles to redirect-to coincide with handles to
  221. # redirect, we need to use saved variants:
  222. $fd->{handle}->fdopen($saved{fileno $fd->{open_as}} || $fd->{open_as},
  223. $fd->{mode});
  224. }
  225. unless ($^O eq 'MSWin32') {
  226. # Stderr may be redirected below, so we save the err text:
  227. foreach $fd (@$close_in_child) {
  228. fcntl($fd, Fcntl::F_SETFD(), 1) or push @errs, "fcntl $fd: $!"
  229. unless $saved{fileno $fd}; # Do not close what we redirect!
  230. }
  231. }
  232. unless (@errs) {
  233. $pid = eval { system 1, @_ }; # 1 == P_NOWAIT
  234. push @errs, "IO::Pipe: Can't spawn-NOWAIT: $!" if !$pid || $pid < 0;
  235. }
  236. foreach $fd (@$fds) {
  237. $fd->{handle}->fdopen($fd->{tmp_copy}, $fd->{mode});
  238. $fd->{tmp_copy}->close or croak "Can't close: $!";
  239. }
  240. croak join "\n", @errs if @errs;
  241. return $pid;
  242. }
  243. 1; # so require is happy