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

/user/perl/lib/IPC/Open3.pm

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