Leaked source code of windows server 2003
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.

333 lines
10 KiB

  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.0103;
  9. @ISA = qw(Exporter);
  10. @EXPORT = qw(open3);
  11. =head1 NAME
  12. IPC::Open3, open3 - open a process for reading, writing, and error handling
  13. =head1 SYNOPSIS
  14. $pid = open3(\*WTRFH, \*RDRFH, \*ERRFH,
  15. 'some cmd and args', 'optarg', ...);
  16. my($wtr, $rdr, $err);
  17. $pid = open3($wtr, $rdr, $err,
  18. 'some cmd and args', 'optarg', ...);
  19. =head1 DESCRIPTION
  20. Extremely similar to open2(), open3() spawns the given $cmd and
  21. connects RDRFH for reading, WTRFH for writing, and ERRFH for errors. If
  22. ERRFH is false, or the same file descriptor as RDRFH, then STDOUT and
  23. STDERR of the child are on the same filehandle. The WTRFH will have
  24. autoflush turned on.
  25. If WTRFH begins with C<< <& >>, then WTRFH will be closed in the parent, and
  26. the child will read from it directly. If RDRFH or ERRFH begins with
  27. C<< >& >>, then the child will send output directly to that filehandle.
  28. In both cases, there will be a dup(2) instead of a pipe(2) made.
  29. If either reader or writer is the null string, this will be replaced
  30. by an autogenerated filehandle. If so, you must pass a valid lvalue
  31. in the parameter slot so it can be overwritten in the caller, or
  32. an exception will be raised.
  33. The filehandles may also be integers, in which case they are understood
  34. as file descriptors.
  35. open3() returns the process ID of the child process. It doesn't return on
  36. failure: it just raises an exception matching C</^open3:/>. However,
  37. C<exec> failures in the child are not detected. You'll have to
  38. trap SIGPIPE yourself.
  39. open3() does not wait for and reap the child process after it exits.
  40. Except for short programs where it's acceptable to let the operating system
  41. take care of this, you need to do this yourself. This is normally as
  42. simple as calling C<waitpid $pid, 0> when you're done with the process.
  43. Failing to do this can result in an accumulation of defunct or "zombie"
  44. processes. See L<perlfunc/waitpid> for more information.
  45. If you try to read from the child's stdout writer and their stderr
  46. writer, you'll have problems with blocking, which means you'll want
  47. to use select() or the IO::Select, which means you'd best use
  48. sysread() instead of readline() for normal stuff.
  49. This is very dangerous, as you may block forever. It assumes it's
  50. going to talk to something like B<bc>, both writing to it and reading
  51. from it. This is presumably safe because you "know" that commands
  52. like B<bc> will read a line at a time and output a line at a time.
  53. Programs like B<sort> that read their entire input stream first,
  54. however, are quite apt to cause deadlock.
  55. The big problem with this approach is that if you don't have control
  56. over source code being run in the child process, you can't control
  57. what it does with pipe buffering. Thus you can't just open a pipe to
  58. C<cat -v> and continually read and write a line from it.
  59. =head1 WARNING
  60. The order of arguments differs from that of open2().
  61. =cut
  62. # &open3: Marc Horowitz <[email protected]>
  63. # derived mostly from &open2 by tom christiansen, <[email protected]>
  64. # fixed for 5.001 by Ulrich Kunitz <[email protected]>
  65. # ported to Win32 by Ron Schmidt, Merrill Lynch almost ended my career
  66. # fixed for autovivving FHs, tchrist again
  67. # allow fd numbers to be used, by Frank Tobin
  68. #
  69. # $Id: open3.pl,v 1.1 1993/11/23 06:26:15 marc Exp $
  70. #
  71. # usage: $pid = open3('wtr', 'rdr', 'err' 'some cmd and args', 'optarg', ...);
  72. #
  73. # spawn the given $cmd and connect rdr for
  74. # reading, wtr for writing, and err for errors.
  75. # if err is '', or the same as rdr, then stdout and
  76. # stderr of the child are on the same fh. returns pid
  77. # of child (or dies on failure).
  78. # if wtr begins with '<&', then wtr will be closed in the parent, and
  79. # the child will read from it directly. if rdr or err begins with
  80. # '>&', then the child will send output directly to that fd. In both
  81. # cases, there will be a dup() instead of a pipe() made.
  82. # WARNING: this is dangerous, as you may block forever
  83. # unless you are very careful.
  84. #
  85. # $wtr is left unbuffered.
  86. #
  87. # abort program if
  88. # rdr or wtr are null
  89. # a system call fails
  90. our $Me = 'open3 (bug)'; # you should never see this, it's always localized
  91. # Fatal.pm needs to be fixed WRT prototypes.
  92. sub xfork {
  93. my $pid = fork;
  94. defined $pid or croak "$Me: fork failed: $!";
  95. return $pid;
  96. }
  97. sub xpipe {
  98. pipe $_[0], $_[1] or croak "$Me: pipe($_[0], $_[1]) failed: $!";
  99. }
  100. # I tried using a * prototype character for the filehandle but it still
  101. # disallows a bearword while compiling under strict subs.
  102. sub xopen {
  103. open $_[0], $_[1] or croak "$Me: open($_[0], $_[1]) failed: $!";
  104. }
  105. sub xclose {
  106. close $_[0] or croak "$Me: close($_[0]) failed: $!";
  107. }
  108. sub fh_is_fd {
  109. return $_[0] =~ /\A=?(\d+)\z/;
  110. }
  111. sub xfileno {
  112. return $1 if $_[0] =~ /\A=?(\d+)\z/; # deal with fh just being an fd
  113. return fileno $_[0];
  114. }
  115. my $do_spawn = $^O eq 'os2' || $^O eq 'MSWin32';
  116. sub _open3 {
  117. local $Me = shift;
  118. my($package, $dad_wtr, $dad_rdr, $dad_err, @cmd) = @_;
  119. my($dup_wtr, $dup_rdr, $dup_err, $kidpid);
  120. # simulate autovivification of filehandles because
  121. # it's too ugly to use @_ throughout to make perl do it for us
  122. # tchrist 5-Mar-00
  123. unless (eval {
  124. $dad_wtr = $_[1] = gensym unless defined $dad_wtr && length $dad_wtr;
  125. $dad_rdr = $_[2] = gensym unless defined $dad_rdr && length $dad_rdr;
  126. 1; })
  127. {
  128. # must strip crud for croak to add back, or looks ugly
  129. $@ =~ s/(?<=value attempted) at .*//s;
  130. croak "$Me: $@";
  131. }
  132. $dad_err ||= $dad_rdr;
  133. $dup_wtr = ($dad_wtr =~ s/^[<>]&//);
  134. $dup_rdr = ($dad_rdr =~ s/^[<>]&//);
  135. $dup_err = ($dad_err =~ s/^[<>]&//);
  136. # force unqualified filehandles into caller's package
  137. $dad_wtr = qualify $dad_wtr, $package unless fh_is_fd($dad_wtr);
  138. $dad_rdr = qualify $dad_rdr, $package unless fh_is_fd($dad_rdr);
  139. $dad_err = qualify $dad_err, $package unless fh_is_fd($dad_err);
  140. my $kid_rdr = gensym;
  141. my $kid_wtr = gensym;
  142. my $kid_err = gensym;
  143. xpipe $kid_rdr, $dad_wtr if !$dup_wtr;
  144. xpipe $dad_rdr, $kid_wtr if !$dup_rdr;
  145. xpipe $dad_err, $kid_err if !$dup_err && $dad_err ne $dad_rdr;
  146. $kidpid = $do_spawn ? -1 : xfork;
  147. if ($kidpid == 0) { # Kid
  148. # If she wants to dup the kid's stderr onto her stdout I need to
  149. # save a copy of her stdout before I put something else there.
  150. if ($dad_rdr ne $dad_err && $dup_err
  151. && xfileno($dad_err) == fileno(STDOUT)) {
  152. my $tmp = gensym;
  153. xopen($tmp, ">&$dad_err");
  154. $dad_err = $tmp;
  155. }
  156. if ($dup_wtr) {
  157. xopen \*STDIN, "<&$dad_wtr" if fileno(STDIN) != xfileno($dad_wtr);
  158. } else {
  159. xclose $dad_wtr;
  160. xopen \*STDIN, "<&=" . fileno $kid_rdr;
  161. }
  162. if ($dup_rdr) {
  163. xopen \*STDOUT, ">&$dad_rdr" if fileno(STDOUT) != xfileno($dad_rdr);
  164. } else {
  165. xclose $dad_rdr;
  166. xopen \*STDOUT, ">&=" . fileno $kid_wtr;
  167. }
  168. if ($dad_rdr ne $dad_err) {
  169. if ($dup_err) {
  170. # I have to use a fileno here because in this one case
  171. # I'm doing a dup but the filehandle might be a reference
  172. # (from the special case above).
  173. xopen \*STDERR, ">&" . xfileno($dad_err)
  174. if fileno(STDERR) != xfileno($dad_err);
  175. } else {
  176. xclose $dad_err;
  177. xopen \*STDERR, ">&=" . fileno $kid_err;
  178. }
  179. } else {
  180. xopen \*STDERR, ">&STDOUT" if fileno(STDERR) != fileno(STDOUT);
  181. }
  182. local($")=(" ");
  183. exec @cmd # XXX: wrong process to croak from
  184. or croak "$Me: exec of @cmd failed";
  185. } elsif ($do_spawn) {
  186. # All the bookkeeping of coincidence between handles is
  187. # handled in spawn_with_handles.
  188. my @close;
  189. if ($dup_wtr) {
  190. $kid_rdr = \*{$dad_wtr};
  191. push @close, $kid_rdr;
  192. } else {
  193. push @close, \*{$dad_wtr}, $kid_rdr;
  194. }
  195. if ($dup_rdr) {
  196. $kid_wtr = \*{$dad_rdr};
  197. push @close, $kid_wtr;
  198. } else {
  199. push @close, \*{$dad_rdr}, $kid_wtr;
  200. }
  201. if ($dad_rdr ne $dad_err) {
  202. if ($dup_err) {
  203. $kid_err = \*{$dad_err};
  204. push @close, $kid_err;
  205. } else {
  206. push @close, \*{$dad_err}, $kid_err;
  207. }
  208. } else {
  209. $kid_err = $kid_wtr;
  210. }
  211. require IO::Pipe;
  212. $kidpid = eval {
  213. spawn_with_handles( [ { mode => 'r',
  214. open_as => $kid_rdr,
  215. handle => \*STDIN },
  216. { mode => 'w',
  217. open_as => $kid_wtr,
  218. handle => \*STDOUT },
  219. { mode => 'w',
  220. open_as => $kid_err,
  221. handle => \*STDERR },
  222. ], \@close, @cmd);
  223. };
  224. die "$Me: $@" if $@;
  225. }
  226. xclose $kid_rdr if !$dup_wtr;
  227. xclose $kid_wtr if !$dup_rdr;
  228. xclose $kid_err if !$dup_err && $dad_rdr ne $dad_err;
  229. # If the write handle is a dup give it away entirely, close my copy
  230. # of it.
  231. xclose $dad_wtr if $dup_wtr;
  232. select((select($dad_wtr), $| = 1)[0]); # unbuffer pipe
  233. $kidpid;
  234. }
  235. sub open3 {
  236. if (@_ < 4) {
  237. local $" = ', ';
  238. croak "open3(@_): not enough arguments";
  239. }
  240. return _open3 'open3', scalar caller, @_
  241. }
  242. sub spawn_with_handles {
  243. my $fds = shift; # Fields: handle, mode, open_as
  244. my $close_in_child = shift;
  245. my ($fd, $pid, @saved_fh, $saved, %saved, @errs);
  246. require Fcntl;
  247. foreach $fd (@$fds) {
  248. $fd->{tmp_copy} = IO::Handle->new_from_fd($fd->{handle}, $fd->{mode});
  249. $saved{fileno $fd->{handle}} = $fd->{tmp_copy};
  250. }
  251. foreach $fd (@$fds) {
  252. bless $fd->{handle}, 'IO::Handle'
  253. unless eval { $fd->{handle}->isa('IO::Handle') } ;
  254. # If some of handles to redirect-to coincide with handles to
  255. # redirect, we need to use saved variants:
  256. $fd->{handle}->fdopen($saved{fileno $fd->{open_as}} || $fd->{open_as},
  257. $fd->{mode});
  258. }
  259. unless ($^O eq 'MSWin32') {
  260. # Stderr may be redirected below, so we save the err text:
  261. foreach $fd (@$close_in_child) {
  262. fcntl($fd, Fcntl::F_SETFD(), 1) or push @errs, "fcntl $fd: $!"
  263. unless $saved{fileno $fd}; # Do not close what we redirect!
  264. }
  265. }
  266. unless (@errs) {
  267. $pid = eval { system 1, @_ }; # 1 == P_NOWAIT
  268. push @errs, "IO::Pipe: Can't spawn-NOWAIT: $!" if !$pid || $pid < 0;
  269. }
  270. foreach $fd (@$fds) {
  271. $fd->{handle}->fdopen($fd->{tmp_copy}, $fd->{mode});
  272. $fd->{tmp_copy}->close or croak "Can't close: $!";
  273. }
  274. croak join "\n", @errs if @errs;
  275. return $pid;
  276. }
  277. 1; # so require is happy