PageRenderTime 27ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/chromium/third_party/cygwin/lib/perl5/5.10/IPC/Open3.pm

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