blib/lib/IPC/Run.pm

filter: Statementstmt 85.2% 1065 / 1249 Branchbran 60.3% 548 / 908 Conditioncond 58.1% 193 / 332 MC/DCmcdc 36.9% 68 / 184 Subroutinesub 96.4% 81 / 84 Podpod 100% 24 / 24 totaltotal 71.1% 1979 / 2781 CC 620 SCAR 50.0
CC
620
Cov
73%
_select_loop
809.6
_waitpid
168.3
harness
154.3
CRAP 148.2
« blib/lib/IPC/Run/Win32Helper.pm ↑ Summary blib/lib/IPC/Run/Win32IO.pm »
1 package IPC::Run;
2 127 ▶use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 =pod
5  
6 =head1 NAME
7  
8 IPC::Run - system() and background procs w/ piping, redirs, ptys (Unix, Win32)
9  
10 =head1 SYNOPSIS
11  
12 ## First,a command to run:
13 my @cat = qw( cat );
14  
15 ## Using run() instead of system():
16 use IPC::Run qw( run timeout );
17  
18 run \@cat, \$in, \$out, \$err, timeout( 10 ) or die "cat: $?";
19  
20 # Can do I/O to sub refs and filenames, too:
21 run \@cat, '<', "in.txt", \&out, \&err or die "cat: $?";
22 run \@cat, '<', "in.txt", '>>', "out.txt", '2>>', "err.txt";
23  
24  
25 # Redirecting using pseudo-terminals instead of pipes.
26 run \@cat, '<pty<', \$in, '>pty>', \$out_and_err;
27  
28 ## Scripting subprocesses (like Expect):
29  
30 use IPC::Run qw( start pump finish timeout );
31  
32 # Incrementally read from / write to scalars.
33 # $in is drained as it is fed to cat's stdin,
34 # $out accumulates cat's stdout
35 # $err accumulates cat's stderr
36 # $h is for "harness".
37 my $h = start \@cat, \$in, \$out, \$err, timeout( 10 );
38  
39 $in .= "some input\n";
40 pump $h until $out =~ /input\n/g;
41  
42 $in .= "some more input\n";
43 pump $h until $out =~ /\G.*more input\n/;
44  
45 $in .= "some final input\n";
46 finish $h or die "cat returned $?";
47  
48 warn $err if $err;
49 print $out; ## All of cat's output
50  
51 # Piping between children
52 run \@cat, '|', \@gzip;
53  
54 # Multiple children simultaneously (run() blocks until all
55 # children exit, use start() for background execution):
56 run \@foo1, '&', \@foo2;
57  
58 # Calling \&set_up_child in the child before it executes the
59 # command (only works on systems with true fork() & exec())
60 # exceptions thrown in set_up_child() will be propagated back
61 # to the parent and thrown from run().
62 run \@cat, \$in, \$out,
63 init => \&set_up_child;
64  
65 # Read from / write to file handles you open and close
66 open IN, '<in.txt' or die $!;
67 open OUT, '>out.txt' or die $!;
68 print OUT "preamble\n";
69 run \@cat, \*IN, \*OUT or die "cat returned $?";
70 print OUT "postamble\n";
71 close IN;
72 close OUT;
73  
74 # Create pipes for you to read / write (like IPC::Open2 & 3).
75 $h = start
76 \@cat,
77 '<pipe', \*IN, # may also be a lexical filehandle e.g. \my $infh
78 '>pipe', \*OUT,
79 '2>pipe', \*ERR
80 or die "cat returned $?";
81 print IN "some input\n";
82 close IN;
83 print <OUT>, <ERR>;
84 finish $h;
85  
86 # Mixing input and output modes
87 run \@cat, 'in.txt', \&catch_some_out, \*ERR_LOG;
88  
89 # Other redirection constructs
90 run \@cat, '>&', \$out_and_err;
91 run \@cat, '2>&1';
92 run \@cat, '0<&3';
93 run \@cat, '<&-';
94 run \@cat, '3<', \$in3;
95 run \@cat, '4>', \$out4;
96 # etc.
97  
98 # Passing options:
99 run \@cat, 'in.txt', debug => 1;
100  
101 # Call this system's shell, returns TRUE on 0 exit code
102 # THIS IS THE OPPOSITE SENSE OF system()'s RETURN VALUE
103 run "cat a b c" or die "cat returned $?";
104  
105 # Launch a sub process directly, no shell. Can't do redirection
106 # with this form, it's here to behave like system() with an
107 # inverted result.
108 $r = run "cat a b c";
109  
110 # Read from a file in to a scalar
111 run io( "filename", 'r', \$recv );
112 run io( \*HANDLE, 'r', \$recv );
113  
114 =head1 DESCRIPTION
115  
116 IPC::Run allows you to run and interact with child processes using files, pipes,
117 and pseudo-ttys. Both system()-style and scripted usages are supported and
118 may be mixed. Likewise, functional and OO API styles are both supported and
119 may be mixed.
120  
121 Various redirection operators reminiscent of those seen on common Unix and DOS
122 command lines are provided.
123  
124 =head1 SIMPLE QUICKSTART
125  
126 Here's a quick guide to basic usage of using IPC::Run's C<run()> function.
127  
128 =head2 Capturing output and errors from an external command
129  
130 Say you want to run a command in your shell. We'll use C<ls> for
131 simplicity, although there are far better ways to get a list of files, such
132 as the C<glob()> function or the L<File::Find> module.
133  
134 The basic form of C<run()> has the command and its arguments passed as an
135 arrayref in the first argument. The command cannot be a single string.
136  
137 @cmd = [ 'ls', '-a', '-l', '-r', '-t' ]; # Yes
138 @cmd = ( 'ls -a -l -r -t' ); # No
139  
140 After the command, pass a scalar reference C<\$in> for the input to pass
141 in, and scalar references C<\$out> and C<\$err> to receive the content of
142 stdout and stderr.
143  
144 use IPC::Run qw( run );
145  
146 @cmd = qw( ls -l -a -r -t );
147 run( \@cmd, \$in, \$out, \$err ) or die $?;
148  
149 print("\$err is ", length($err), " bytes long\n");
150 print($err, "\n");
151  
152 print("\$out is ", length($out), " bytes long\n");
153 print($out, "\n");
154  
155 Running this will show something like:
156  
157 $err is 0 bytes long
158  
159 $out is 1410 bytes long
160 total 392
161 drwxr-xr-x 3 andy staff 96 Mar 17 11:53 .github
162 -rw-r--r-- 1 andy staff 158 Mar 17 11:53 .gitignore
163 ... etc ...
164  
165 Note that C<$out> and C<$err> are always defined after a call to C<run()>,
166 even if they receive no data.
167  
168 =head2 Passing input to the external program
169  
170 If you have input to pass in, put it in the C<$in> variables. For example,
171 to use the C<wc> command to count lines, words and characters in a block of
172 text:
173  
174 $in = <<'CARROLL';
175 'Twas brillig, and the slithy toves
176 Did gyre and gimble in the wabe:
177 All mimsy were the borogoves,
178 And the mome raths outgrabe.
179 CARROLL
180  
181 @cmd = qw( wc );
182 run( \@cmd, \$in, \$out, \$err ) or die $?;
183 print "$out";
184  
185 This gives the output:
186  
187 4 23 140
188  
189 =head2 Handling errors
190  
191 It's important to check the return code of C<run()> to see if the command
192 ran successfully. C<run()> returns a boolean true on success, and false on
193 failure. Note that this is the opposite of Perl's C<system()>, which
194 returns 0 on success and a non-zero value on failures.
195  
196 For the specific subprocess error code, check C<$?> directly.
197  
198 @cmd = qw( tar xzvf nonexistent.tar );
199 if ( !run( \@cmd, \$in, \$out, \$err ) ) {
200 print "\$? = $?\n";
201 print "err = $err\n";
202 }
203  
204 Running this gives:
205  
206 $? = 256
207 err = tar: Error opening archive: Failed to open 'nonexistent.tar'
208  
209 If the program does not exist, then C<run()> will C<die> and won't return
210 at all. For example:
211  
212 @cmd = qw( bogus-command );
213 my $rc = run( \@cmd, \$in, \$out, \$err );
214 print "run returned ", ($rc ? "true" : "false"), "\n";
215  
216 Running this doesn't make it to the C<print> statement.
217  
218 Command 'bogus-command' not found in [ list of paths ] at program.pl line N.
219  
220 To handle the possibility of a non-existent program, call C<run()> inside
221 an C<eval>.
222  
223 my $rc;
224 eval { $rc = run( \@cmd, \$in, \$out, \$out ); 1; };
225 if ( !defined($rc) ) {
226 print "run died: $@\n";
227 }
228 else {
229 if ( $rc ) {
230 print "run returned true\n";
231 }
232 else {
233 print "run returned false\n";
234 print "\$? = $?\n";
235 }
236 }
237  
238 =head2 And beyond
239  
240 That's the basics of using C<run()> as a replacement for C<system()>. If you'd
241 like to do more, such as having subprocesses communicate with each other,
242 setting timeouts on long-running processes, kill running subprocesses,
243 redirecting output, closing file descriptors and much much MUCH more, read on.
244  
245 =head1 THE DETAILS
246  
247 Before digging in to the details a few LIMITATIONS are important enough
248 to be mentioned right up front:
249  
250 =over
251  
252 =item Win32 Support
253  
254 Win32 support is working but B<EXPERIMENTAL>, but does pass all relevant tests
255 on NT 4.0. See L</Win32 LIMITATIONS>.
256  
257 =item pty Support
258  
259 If you need pty support, IPC::Run should work well enough most of the
260 time, but IO::Pty is being improved, and IPC::Run will be improved to
261 use IO::Pty's new features when it is released.
262  
263 The basic problem is that the pty needs to initialize itself before the
264 parent writes to the master pty, or the data written gets lost. So
265 IPC::Run does a sleep(1) in the parent after forking to (hopefully) give
266 the child a chance to run. This is a kludge that works well on non
267 heavily loaded systems :(.
268  
269 ptys are not supported yet under Win32, but will be emulated...
270  
271 =item Debugging Tip
272  
273 You may use the environment variable C<IPCRUNDEBUG> to see what's going on
274 under the hood:
275  
276 $ IPCRUNDEBUG=basic myscript # prints minimal debugging
277 $ IPCRUNDEBUG=data myscript # prints all data reads/writes
278 $ IPCRUNDEBUG=details myscript # prints lots of low-level details
279 $ IPCRUNDEBUG=gory myscript # (Win32 only) prints data moving through
280 # the helper processes.
281  
282 =back
283  
284 =head2 Harnesses
285  
286 Child processes and I/O handles are gathered in to a harness, then
287 started and run until the processing is finished or aborted.
288  
289 =head2 run() vs. start(); pump(); finish();
290  
291 There are two modes you can run harnesses in: run() functions as an
292 enhanced system(), and start()/pump()/finish() allow for background
293 processes and scripted interactions with them.
294  
295 When using run(), all data to be sent to the harness is set up in
296 advance (though one can feed subprocesses input from subroutine refs to
297 get around this limitation). The harness is run and all output is
298 collected from it, then any child processes are waited for:
299  
300 run \@cmd, \<<IN, \$out;
301 blah
302 IN
303  
304 ## To precompile harnesses and run them later:
305 my $h = harness \@cmd, \<<IN, \$out;
306 blah
307 IN
308  
309 run $h;
310  
311 The background and scripting API is provided by start(), pump(), and
312 finish(): start() creates a harness if need be (by calling harness())
313 and launches any subprocesses, pump() allows you to poll them for
314 activity, and finish() then monitors the harnessed activities until they
315 complete.
316  
317 ## Build the harness, open all pipes, and launch the subprocesses
318 my $h = start \@cat, \$in, \$out;
319 $in = "first input\n";
320  
321 ## Now do I/O. start() does no I/O.
322 pump $h while length $in; ## Wait for all input to go
323  
324 ## Now do some more I/O.
325 $in = "second input\n";
326 pump $h until $out =~ /second input/;
327  
328 ## Clean up
329 finish $h or die "cat returned $?";
330  
331 You can optionally compile the harness with harness() prior to
332 start()ing or run()ing, and you may omit start() between harness() and
333 pump(). You might want to do these things if you compile your harnesses
334 ahead of time.
335  
336 =head2 Using regexps to match output
337  
338 As shown in most of the scripting examples, the read-to-scalar facility
339 for gathering subcommand's output is often used with regular expressions
340 to detect stopping points. This is because subcommand output often
341 arrives in dribbles and drabs, often only a character or line at a time.
342 This output is input for the main program and piles up in variables like
343 the C<$out> and C<$err> in our examples.
344  
345 Regular expressions can be used to wait for appropriate output in
346 several ways. The C<cat> example in the previous section demonstrates
347 how to pump() until some string appears in the output. Here's an
348 example that uses C<smb> to fetch files from a remote server:
349  
350 $h = harness \@smbclient, \$in, \$out;
351  
352 $in = "cd /src\n";
353 $h->pump until $out =~ /^smb.*> \Z/m;
354 die "error cding to /src:\n$out" if $out =~ "ERR";
355 $out = '';
356  
357 $in = "mget *\n";
358 $h->pump until $out =~ /^smb.*> \Z/m;
359 die "error retrieving files:\n$out" if $out =~ "ERR";
360  
361 $in = "quit\n";
362 $h->finish;
363  
364 Notice that we carefully clear $out after the first command/response
365 cycle? That's because IPC::Run does not delete $out when we continue,
366 and we don't want to trip over the old output in the second
367 command/response cycle.
368  
369 Say you want to accumulate all the output in $out and analyze it
370 afterwards. Perl offers incremental regular expression matching using
371 the C<m//gc> and pattern matching idiom and the C<\G> assertion.
372 IPC::Run is careful not to disturb the current C<pos()> value for
373 scalars it appends data to, so we could modify the above so as not to
374 destroy $out by adding a couple of C</gc> modifiers. The C</g> keeps us
375 from tripping over the previous prompt and the C</c> keeps us from
376 resetting the prior match position if the expected prompt doesn't
377 materialize immediately:
378  
379 $h = harness \@smbclient, \$in, \$out;
380  
381 $in = "cd /src\n";
382 $h->pump until $out =~ /^smb.*> \Z/mgc;
383 die "error cding to /src:\n$out" if $out =~ "ERR";
384  
385 $in = "mget *\n";
386 $h->pump until $out =~ /^smb.*> \Z/mgc;
387 die "error retrieving files:\n$out" if $out =~ "ERR";
388  
389 $in = "quit\n";
390 $h->finish;
391  
392 analyze( $out );
393  
394 When using this technique, you may want to preallocate $out to have
395 plenty of memory or you may find that the act of growing $out each time
396 new input arrives causes an C<O(length($out)^2)> slowdown as $out grows.
397 Say we expect no more than 10,000 characters of input at the most. To
398 preallocate memory to $out, do something like:
399  
400 my $out = "x" x 10_000;
401 $out = "";
402  
403 C<perl> will allocate at least 10,000 characters' worth of space, then
404 mark the $out as having 0 length without freeing all that yummy RAM.
405  
406 =head2 Timeouts and Timers
407  
408 More than likely, you don't want your subprocesses to run forever, and
409 sometimes it's nice to know that they're going a little slowly.
410 Timeouts throw exceptions after a some time has elapsed, timers merely
411 cause pump() to return after some time has elapsed. Neither is
412 reset/restarted automatically.
413  
414 Timeout objects are created by calling timeout( $interval ) and passing
415 the result to run(), start() or harness(). The timeout period starts
416 ticking just after all the child processes have been fork()ed or
417 spawn()ed, and are polled for expiration in run(), pump() and finish().
418 If/when they expire, an exception is thrown. This is typically useful
419 to keep a subprocess from taking too long.
420  
421 If a timeout occurs in run(), all child processes will be terminated and
422 all file/pipe/ptty descriptors opened by run() will be closed. File
423 descriptors opened by the parent process and passed in to run() are not
424 closed in this event.
425  
426 If a timeout occurs in pump(), pump_nb(), or finish(), it's up to you to
427 decide whether to kill_kill() all the children or to implement some more
428 graceful fallback. No I/O will be closed in pump(), pump_nb() or
429 finish() by such an exception (though I/O is often closed down in those
430 routines during the natural course of events).
431  
432 Often an exception is too harsh. timer( $interval ) creates timer
433 objects that merely prevent pump() from blocking forever. This can be
434 useful for detecting stalled I/O or printing a soothing message or "."
435 to pacify an anxious user.
436  
437 Timeouts and timers can both be restarted at any time using the timer's
438 start() method (this is not the start() that launches subprocesses). To
439 restart a timer, you need to keep a reference to the timer:
440  
441 ## Start with a nice long timeout to let smbclient connect. If
442 ## pump or finish take too long, an exception will be thrown.
443  
444 my $h;
445 eval {
446 $h = harness \@smbclient, \$in, \$out, \$err, ( my $t = timeout 30 );
447 sleep 11; # No effect: timer not running yet
448  
449 start $h;
450 $in = "cd /src\n";
451 pump $h until ! length $in;
452  
453 $in = "ls\n";
454 ## Now use a short timeout, since this should be faster
455 $t->start( 5 );
456 pump $h until ! length $in;
457  
458 $t->start( 10 ); ## Give smbclient a little while to shut down.
459 $h->finish;
460 };
461 if ( $@ ) {
462 my $x = $@; ## Preserve $@ in case another exception occurs
463 $h->kill_kill; ## kill it gently, then brutally if need be, or just
464 ## brutally on Win32.
465 die $x;
466 }
467  
468 Timeouts and timers are I<not> checked once the subprocesses are shut
469 down; they will not expire in the interval between the last valid
470 process and when IPC::Run scoops up the processes' result codes, for
471 instance.
472  
473 =head2 Spawning synchronization, child exception propagation
474  
475 start() pauses the parent until the child executes the command or CODE
476 reference and propagates any exceptions thrown (including exec()
477 failure) back to the parent. This has several pleasant effects: any
478 exceptions thrown in the child, including exec() failure, come flying
479 out of start() or run() as though they had occurred in the parent.
480  
481 This includes exceptions your code thrown from init subs. In this
482 example:
483  
484 eval {
485 run \@cmd, init => sub { die "blast it! foiled again!" };
486 };
487 print $@;
488  
489 the exception "blast it! foiled again" will be thrown from the child
490 process (preventing the exec()) and printed by the parent.
491  
492 In situations like
493  
494 run \@cmd1, "|", \@cmd2, "|", \@cmd3;
495  
496 @cmd1 will be initted and exec()ed before @cmd2, and @cmd2 before @cmd3.
497 This can save time and prevent oddball errors emitted by later commands
498 when earlier commands fail to execute. Note that IPC::Run doesn't start
499 any commands unless it can find the executables referenced by all
500 commands. These executables must pass both the C<-f> and C<-x> tests
501 described in L<perlfunc>.
502  
503 Another nice effect is that init() subs can take their time doing things
504 and there will be no problems caused by a parent continuing to execute
505 before a child's init() routine is complete. Say the init() routine
506 needs to open a socket or a temp file that the parent wants to connect
507 to; without this synchronization, the parent will need to implement a
508 retry loop to wait for the child to run, since often, the parent gets a
509 lot of things done before the child's first timeslice is allocated.
510  
511 This is also quite necessary for pseudo-tty initialization, which needs
512 to take place before the parent writes to the child via pty. Writes
513 that occur before the pty is set up can get lost.
514  
515 A final, minor, nicety is that debugging output from the child will be
516 emitted before the parent continues on, making for much clearer debugging
517 output in complex situations.
518  
519 The only drawback I can conceive of is that the parent can't continue to
520 operate while the child is being initted. If this ever becomes a
521 problem in the field, we can implement an option to avoid this behavior,
522 but I don't expect it to.
523  
524 B<Win32>: executing CODE references isn't supported on Win32, see
525 L</Win32 LIMITATIONS> for details.
526  
527 =head2 Syntax
528  
529 run(), start(), and harness() can all take a harness specification
530 as input. A harness specification is either a single string to be passed
531 to the systems' shell:
532  
533 run "echo 'hi there'";
534  
535 or a list of commands, io operations, and/or timers/timeouts to execute.
536 Consecutive commands must be separated by a pipe operator '|' or an '&'.
537 External commands are passed in as array references or L<IPC::Run::Win32Process>
538 objects. On systems supporting fork(), Perl code may be passed in as subs:
539  
540 run \@cmd;
541 run \@cmd1, '|', \@cmd2;
542 run \@cmd1, '&', \@cmd2;
543 run \&sub1;
544 run \&sub1, '|', \&sub2;
545 run \&sub1, '&', \&sub2;
546  
547 '|' pipes the stdout of \@cmd1 the stdin of \@cmd2, just like a
548 shell pipe. '&' does not. Child processes to the right of a '&'
549 will have their stdin closed unless it's redirected-to.
550  
551 L<IPC::Run::IO> objects may be passed in as well, whether or not
552 child processes are also specified:
553  
554 run io( "infile", ">", \$in ), io( "outfile", "<", \$in );
555
556 as can L<IPC::Run::Timer> objects:
557  
558 run \@cmd, io( "outfile", "<", \$in ), timeout( 10 );
559  
560 Commands may be followed by scalar, sub, or i/o handle references for
561 redirecting
562 child process input & output:
563  
564 run \@cmd, \undef, \$out;
565 run \@cmd, \$in, \$out;
566 run \@cmd1, \&in, '|', \@cmd2, \*OUT;
567 run \@cmd1, \*IN, '|', \@cmd2, \&out;
568  
569 This is known as succinct redirection syntax, since run(), start()
570 and harness(), figure out which file descriptor to redirect and how.
571 File descriptor 0 is presumed to be an input for
572 the child process, all others are outputs. The assumed file
573 descriptor always starts at 0, unless the command is being piped to,
574 in which case it starts at 1.
575  
576 To be explicit about your redirects, or if you need to do more complex
577 things, there's also a redirection operator syntax:
578  
579 run \@cmd, '<', \undef, '>', \$out;
580 run \@cmd, '<', \undef, '>&', \$out_and_err;
581 run(
582 \@cmd1,
583 '<', \$in,
584 '|', \@cmd2,
585 \$out
586 );
587  
588 Operator syntax is required if you need to do something other than simple
589 redirection to/from scalars or subs, like duping or closing file descriptors
590 or redirecting to/from a named file. The operators are covered in detail
591 below.
592  
593 After each \@cmd (or \&foo), parsing begins in succinct mode and toggles to
594 operator syntax mode when an operator (ie plain scalar, not a ref) is seen.
595 Once in
596 operator syntax mode, parsing only reverts to succinct mode when a '|' or
597 '&' is seen.
598  
599 In succinct mode, each parameter after the \@cmd specifies what to
600 do with the next highest file descriptor. These File descriptor start
601 with 0 (stdin) unless stdin is being piped to (C<'|', \@cmd>), in which
602 case they start with 1 (stdout). Currently, being on the left of
603 a pipe (C<\@cmd, \$out, \$err, '|'>) does I<not> cause stdout to be
604 skipped, though this may change since it's not as DWIMerly as it
605 could be. Only stdin is assumed to be an
606 input in succinct mode, all others are assumed to be outputs.
607  
608 If no piping or redirection is specified for a child, it will inherit
609 the parent's open file handles as dictated by your system's
610 close-on-exec behavior and the $^F flag, except that processes after a
611 '&' will not inherit the parent's stdin. Also note that $^F does not
612 affect file descriptors obtained via POSIX, since it only applies to
613 full-fledged Perl file handles. Such processes will have their stdin
614 closed unless it has been redirected-to.
615  
616 If you want to close a child processes stdin, you may do any of:
617  
618 run \@cmd, \undef;
619 run \@cmd, \"";
620 run \@cmd, '<&-';
621 run \@cmd, '0<&-';
622  
623 Redirection is done by placing redirection specifications immediately
624 after a command or child subroutine:
625  
626 run \@cmd1, \$in, '|', \@cmd2, \$out;
627 run \@cmd1, '<', \$in, '|', \@cmd2, '>', \$out;
628  
629 If you omit the redirection operators, descriptors are counted
630 starting at 0. Descriptor 0 is assumed to be input, all others
631 are outputs. A leading '|' consumes descriptor 0, so this
632 works as expected.
633  
634 run \@cmd1, \$in, '|', \@cmd2, \$out;
635
636 The parameter following a redirection operator can be a scalar ref,
637 a subroutine ref, a file name, an open filehandle, or a closed
638 filehandle.
639  
640 If it's a scalar ref, the child reads input from or sends output to
641 that variable:
642  
643 $in = "Hello World.\n";
644 run \@cat, \$in, \$out;
645 print $out;
646  
647 Scalars used in incremental (start()/pump()/finish()) applications are treated
648 as queues: input is removed from input scalars, resulting in them dwindling
649 to '', and output is appended to output scalars. This is not true of
650 harnesses run() in batch mode.
651  
652 It's usually wise to append new input to be sent to the child to the input
653 queue, and you'll often want to zap output queues to '' before pumping.
654  
655 $h = start \@cat, \$in;
656 $in = "line 1\n";
657 pump $h;
658 $in .= "line 2\n";
659 pump $h;
660 $in .= "line 3\n";
661 finish $h;
662  
663 The final call to finish() must be there: it allows the child process(es)
664 to run to completion and waits for their exit values.
665  
666 =head1 OBSTINATE CHILDREN
667  
668 Interactive applications are usually optimized for human use. This
669 can help or hinder trying to interact with them through modules like
670 IPC::Run. Frequently, programs alter their behavior when they detect
671 that stdin, stdout, or stderr are not connected to a tty, assuming that
672 they are being run in batch mode. Whether this helps or hurts depends
673 on which optimizations change. And there's often no way of telling
674 what a program does in these areas other than trial and error and
675 occasionally, reading the source. This includes different versions
676 and implementations of the same program.
677  
678 All hope is not lost, however. Most programs behave in reasonably
679 tractable manners, once you figure out what it's trying to do.
680  
681 Here are some of the issues you might need to be aware of.
682  
683 =over
684  
685 =item *
686  
687 fflush()ing stdout and stderr
688  
689 This lets the user see stdout and stderr immediately. Many programs
690 undo this optimization if stdout is not a tty, making them harder to
691 manage by things like IPC::Run.
692  
693 Many programs decline to fflush stdout or stderr if they do not
694 detect a tty there. Some ftp commands do this, for instance.
695  
696 If this happens to you, look for a way to force interactive behavior,
697 like a command line switch or command. If you can't, you will
698 need to use a pseudo terminal ('<pty<' and '>pty>').
699  
700 =item *
701  
702 false prompts
703  
704 Interactive programs generally do not guarantee that output from user
705 commands won't contain a prompt string. For example, your shell prompt
706 might be a '$', and a file named '$' might be the only file in a directory
707 listing.
708  
709 This can make it hard to guarantee that your output parser won't be fooled
710 into early termination of results.
711  
712 To help work around this, you can see if the program can alter its
713 prompt, and use something you feel is never going to occur in actual
714 practice.
715  
716 You should also look for your prompt to be the only thing on a line:
717  
718 pump $h until $out =~ /^<SILLYPROMPT>\s?\z/m;
719  
720 (use C<(?!\n)\Z> in place of C<\z> on older perls).
721  
722 You can also take the approach that IPC::ChildSafe takes and emit a
723 command with known output after each 'real' command you issue, then
724 look for this known output. See new_appender() and new_chunker() for
725 filters that can help with this task.
726  
727 If it's not convenient or possibly to alter a prompt or use a known
728 command/response pair, you might need to autodetect the prompt in case
729 the local version of the child program is different then the one
730 you tested with, or if the user has control over the look & feel of
731 the prompt.
732  
733 =item *
734  
735 Refusing to accept input unless stdin is a tty.
736  
737 Some programs, for security reasons, will only accept certain types
738 of input from a tty. su, notable, will not prompt for a password unless
739 it's connected to a tty.
740  
741 If this is your situation, use a pseudo terminal ('<pty<' and '>pty>').
742  
743 =item *
744  
745 Not prompting unless connected to a tty.
746  
747 Some programs don't prompt unless stdin or stdout is a tty. See if you can
748 turn prompting back on. If not, see if you can come up with a command that
749 you can issue after every real command and look for its output, as
750 IPC::ChildSafe does. There are two filters included with IPC::Run that
751 can help with doing this: appender and chunker (see new_appender() and
752 new_chunker()).
753  
754 =item *
755  
756 Different output format when not connected to a tty.
757  
758 Some commands alter their formats to ease machine parsability when they
759 aren't connected to a pipe. This is actually good, but can be surprising.
760  
761 =back
762  
763 =head1 PSEUDO TERMINALS
764  
765 On systems providing pseudo terminals under /dev, IPC::Run can use IO::Pty
766 (available on CPAN) to provide a terminal environment to subprocesses.
767 This is necessary when the subprocess really wants to think it's connected
768 to a real terminal.
769  
770 =head2 CAVEATS
771  
772 Pseudo-terminals are not pipes, though they are similar. Here are some
773 differences to watch out for.
774  
775 =over
776  
777 =item Echoing
778  
779 Sending to stdin will cause an echo on stdout, which occurs before each
780 line is passed to the child program. There is currently no way to
781 disable this, although the child process can and should disable it for
782 things like passwords.
783  
784 =item Shutdown
785  
786 IPC::Run cannot close a pty until all output has been collected. This
787 means that it is not possible to send an EOF to stdin by half-closing
788 the pty, as we can when using a pipe to stdin.
789  
790 This means that you need to send the child process an exit command or
791 signal, or run() / finish() will time out. Be careful not to expect a
792 prompt after sending the exit command.
793  
794 =item Command line editing
795  
796 Some subprocesses, notable shells that depend on the user's prompt
797 settings, will reissue the prompt plus the command line input so far
798 once for each character.
799  
800 =item '>pty>' means '&>pty>', not '1>pty>'
801  
802 The pseudo terminal redirects both stdout and stderr unless you specify
803 a file descriptor. If you want to grab stderr separately, do this:
804  
805 start \@cmd, '<pty<', \$in, '>pty>', \$out, '2>', \$err;
806  
807 =item stdin, stdout, and stderr not inherited
808  
809 Child processes harnessed to a pseudo terminal have their stdin, stdout,
810 and stderr completely closed before any redirection operators take
811 effect. This casts off the bonds of the controlling terminal. This is
812 not done when using pipes.
813  
814 Right now, this affects all children in a harness that has a pty in use,
815 even if that pty would not affect a particular child. That's a bug and
816 will be fixed. Until it is, it's best not to mix-and-match children.
817  
818 =back
819  
820 =head2 Redirection Operators
821  
822 Operator SHNP Description
823 ======== ==== ===========
824 <, N< SHN Redirects input to a child's fd N (0 assumed)
825  
826 >, N> SHN Redirects output from a child's fd N (1 assumed)
827 >>, N>> SHN Like '>', but appends to scalars or named files
828 >&, &> SHN Redirects stdout & stderr from a child process
829  
830 <pty, N<pty S Like '<', but uses a pseudo-tty instead of a pipe
831 >pty, N>pty S Like '>', but uses a pseudo-tty instead of a pipe
832  
833 N<&M Dups input fd N to input fd M
834 M>&N Dups output fd N to input fd M
835 N<&- Closes fd N
836  
837 <pipe, N<pipe P Pipe opens H for caller to read, write, close.
838 >pipe, N>pipe P Pipe opens H for caller to read, write, close.
839
840 'N' and 'M' are placeholders for integer file descriptor numbers. The
841 terms 'input' and 'output' are from the child process's perspective.
842  
843 The SHNP field indicates what parameters an operator can take:
844  
845 S: \$scalar or \&function references. Filters may be used with
846 these operators (and only these).
847 H: \*HANDLE or IO::Handle for caller to open, and close
848 N: "file name".
849 P: \*HANDLE or lexical filehandle opened by IPC::Run as the parent end of a pipe, but read
850 and written to and closed by the caller (like IPC::Open3).
851  
852 =over
853  
854 =item Redirecting input: [n]<, [n]<pipe
855  
856 You can input the child reads on file descriptor number n to come from a
857 scalar variable, subroutine, file handle, or a named file. If stdin
858 is not redirected, the parent's stdin is inherited.
859  
860 run \@cat, \undef ## Closes child's stdin immediately
861 or die "cat returned $?";
862  
863 run \@cat, \$in;
864  
865 run \@cat, \<<TOHERE;
866 blah
867 TOHERE
868  
869 run \@cat, \&input; ## Calls &input, feeding data returned
870 ## to child's. Closes child's stdin
871 ## when undef is returned.
872  
873 Redirecting from named files requires you to use the input
874 redirection operator:
875  
876 run \@cat, '<.profile';
877 run \@cat, '<', '.profile';
878  
879 open IN, "<foo";
880 run \@cat, \*IN;
881 run \@cat, *IN{IO};
882  
883 The form used second example here is the safest,
884 since filenames like "0" and "&more\n" won't confuse &run:
885  
886 You can't do either of
887  
888 run \@a, *IN; ## INVALID
889 run \@a, '<', *IN; ## BUGGY: Reads file named like "*main::A"
890
891 because perl passes a scalar containing a string that
892 looks like "*main::A" to &run, and &run can't tell the difference
893 between that and a redirection operator or a file name. &run guarantees
894 that any scalar you pass after a redirection operator is a file name.
895  
896 If your child process will take input from file descriptors other
897 than 0 (stdin), you can use a redirection operator with any of the
898 valid input forms (scalar ref, sub ref, etc.):
899  
900 run \@cat, '3<', \$in3;
901  
902 When redirecting input from a scalar ref, the scalar ref is
903 used as a queue. This allows you to use &harness and pump() to
904 feed incremental bits of input to a coprocess. See L</Coprocesses>
905 below for more information.
906  
907 The <pipe operator opens the write half of a pipe on the filehandle
908 glob reference it takes as an argument:
909  
910 $h = start \@cat, '<pipe', \*IN;
911 print IN "hello world\n";
912 pump $h;
913 close IN;
914 finish $h;
915  
916 Unlike the other '<' operators, IPC::Run does nothing further with
917 it: you are responsible for it. The previous example is functionally
918 equivalent to:
919  
920 pipe( \*R, \*IN ) or die $!;
921 $h = start \@cat, '<', \*IN;
922 print IN "hello world\n";
923 pump $h;
924 close IN;
925 finish $h;
926  
927 This is like the behavior of IPC::Open2 and IPC::Open3.
928  
929 B<Win32>: The handle returned is actually a socket handle, so you can
930 use select() on it.
931  
932 =item Redirecting output: [n]>, [n]>>, [n]>&[m], [n]>pipe
933  
934 You can redirect any output the child emits
935 to a scalar variable, subroutine, file handle, or file name. You
936 can have &run truncate or append to named files or scalars. If
937 you are redirecting stdin as well, or if the command is on the
938 receiving end of a pipeline ('|'), you can omit the redirection
939 operator:
940  
941 @ls = ( 'ls' );
942 run \@ls, \undef, \$out
943 or die "ls returned $?";
944  
945 run \@ls, \undef, \&out; ## Calls &out each time some output
946 ## is received from the child's
947 ## when undef is returned.
948  
949 run \@ls, \undef, '2>ls.err';
950 run \@ls, '2>', 'ls.err';
951  
952 The two parameter form guarantees that the filename
953 will not be interpreted as a redirection operator:
954  
955 run \@ls, '>', "&more";
956 run \@ls, '2>', ">foo\n";
957  
958 You can pass file handles you've opened for writing:
959  
960 open( *OUT, ">out.txt" );
961 open( *ERR, ">err.txt" );
962 run \@cat, \*OUT, \*ERR;
963  
964 Passing a scalar reference and a code reference requires a little
965 more work, but allows you to capture all of the output in a scalar
966 or each piece of output by a callback:
967  
968 These two do the same things:
969  
970 run( [ 'ls' ], '2>', sub { $err_out .= $_[0] } );
971  
972 does the same basic thing as:
973  
974 run( [ 'ls' ], '2>', \$err_out );
975  
976 The subroutine will be called each time some data is read from the child.
977  
978 The >pipe operator is different in concept than the other '>' operators,
979 although its syntax is similar:
980  
981 $h = start \@cat, $in, '>pipe', \*OUT, '2>pipe', \*ERR;
982 $in = "hello world\n";
983 finish $h;
984 print <OUT>;
985 print <ERR>;
986 close OUT;
987 close ERR;
988  
989 causes two pipe to be created, with one end attached to cat's stdout
990 and stderr, respectively, and the other left open on OUT and ERR, so
991 that the script can manually
992 read(), select(), etc. on them. This is like
993 the behavior of IPC::Open2 and IPC::Open3.
994  
995 B<Win32>: The handle returned is actually a socket handle, so you can
996 use select() on it.
997  
998 =item Duplicating output descriptors: >&m, n>&m
999  
1000 This duplicates output descriptor number n (default is 1 if n is omitted)
1001 from descriptor number m.
1002  
1003 =item Duplicating input descriptors: <&m, n<&m
1004  
1005 This duplicates input descriptor number n (default is 0 if n is omitted)
1006 from descriptor number m
1007  
1008 =item Closing descriptors: <&-, 3<&-
1009  
1010 This closes descriptor number n (default is 0 if n is omitted). The
1011 following commands are equivalent:
1012  
1013 run \@cmd, \undef;
1014 run \@cmd, '<&-';
1015 run \@cmd, '<in.txt', '<&-';
1016  
1017 Doing
1018  
1019 run \@cmd, \$in, '<&-'; ## SIGPIPE recipe.
1020  
1021 is dangerous: the parent will get a SIGPIPE if $in is not empty.
1022  
1023 =item Redirecting both stdout and stderr: &>, >&, &>pipe, >pipe&
1024  
1025 The following pairs of commands are equivalent:
1026  
1027 run \@cmd, '>&', \$out; run \@cmd, '>', \$out, '2>&1';
1028 run \@cmd, '>&', 'out.txt'; run \@cmd, '>', 'out.txt', '2>&1';
1029  
1030 etc.
1031  
1032 File descriptor numbers are not permitted to the left or the right of
1033 these operators, and the '&' may occur on either end of the operator.
1034  
1035 The '&>pipe' and '>pipe&' variants behave like the '>pipe' operator, except
1036 that both stdout and stderr write to the created pipe.
1037  
1038 =item Redirection Filters
1039  
1040 Both input redirections and output redirections that use scalars or
1041 subs as endpoints may have an arbitrary number of filter subs placed
1042 between them and the child process. This is useful if you want to
1043 receive output in chunks, or if you want to massage each chunk of
1044 data sent to the child. To use this feature, you must use operator
1045 syntax:
1046  
1047 run(
1048 \@cmd
1049 '<', \&in_filter_2, \&in_filter_1, $in,
1050 '>', \&out_filter_1, \&in_filter_2, $out,
1051 );
1052  
1053 This capability is not provided for IO handles or named files.
1054  
1055 Two filters are provided by IPC::Run: appender and chunker. Because
1056 these may take an argument, you need to use the constructor functions
1057 new_appender() and new_chunker() rather than using \& syntax:
1058  
1059 run(
1060 \@cmd
1061 '<', new_appender( "\n" ), $in,
1062 '>', new_chunker, $out,
1063 );
1064  
1065 =back
1066  
1067 =head2 Just doing I/O
1068  
1069 If you just want to do I/O to a handle or file you open yourself, you
1070 may specify a filehandle or filename instead of a command in the harness
1071 specification:
1072  
1073 run io( "filename", '>', \$recv );
1074  
1075 $h = start io( $io, '>', \$recv );
1076  
1077 $h = harness \@cmd, '&', io( "file", '<', \$send );
1078  
1079 =head2 Options
1080  
1081 Options are passed in as name/value pairs:
1082  
1083 run \@cat, \$in, debug => 1;
1084  
1085 If you pass the debug option, you may want to pass it in first, so you
1086 can see what parsing is going on:
1087  
1088 run debug => 1, \@cat, \$in;
1089  
1090 =over
1091  
1092 =item debug
1093  
1094 Enables debugging output in parent and child. Debugging info is emitted
1095 to the STDERR that was present when IPC::Run was first C<use()>ed (it's
1096 C<dup()>ed out of the way so that it can be redirected in children without
1097 having debugging output emitted on it).
1098  
1099 =back
1100  
1101 =head1 RETURN VALUES
1102  
1103 harness() and start() return a reference to an IPC::Run harness. This is
1104 blessed in to the IPC::Run package, so you may make later calls to
1105 functions as members if you like:
1106  
1107 $h = harness( ... );
1108 $h->start;
1109 $h->pump;
1110 $h->finish;
1111  
1112 $h = start( .... );
1113 $h->pump;
1114 ...
1115  
1116 Of course, using method call syntax lets you deal with any IPC::Run
1117 subclasses that might crop up, but don't hold your breath waiting for
1118 any.
1119  
1120 run() and finish() return TRUE when all subcommands exit with a 0 result
1121 code. B<This is the opposite of perl's system() command>.
1122  
1123 All routines raise exceptions (via die()) when error conditions are
1124 recognized. A non-zero command result is not treated as an error
1125 condition, since some commands are tests whose results are reported
1126 in their exit codes.
1127  
1128 =head1 ROUTINES
1129  
1130 =over
1131  
1132 =cut
1133  
1134 127 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
1135 127 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
1136 127 ▶use Exporter ();
Subroutine BEGIN: called CC=1 SCAR=0.0
1137 127 ▶use vars qw{$VERSION @ISA @FILTER_IMP @FILTERS @API @EXPORT_OK %EXPORT_TAGS};
Subroutine BEGIN: called CC=1 SCAR=0.0
1138  
1139 BEGIN {
1140 127 ▶ $VERSION = '20250715.0_01';
Subroutine BEGIN: called CC=1 SCAR=0.0
1141 127 @ISA = qw{ Exporter };
1142  
1143 ## We use @EXPORT for the end user's convenience: there's only one function
1144 ## exported, it's homonymous with the module, it's an unusual name, and
1145 ## it can be suppressed by "use IPC::Run ();".
1146 127 @FILTER_IMP = qw( input_avail get_more_input );
1147 127 @FILTERS = qw(
1148 new_appender
1149 new_chunker
1150 new_string_source
1151 new_string_sink
1152 );
1153 127 @API = qw(
1154 run
1155 harness start pump pumpable finish
1156 signal kill_kill reap_nb
1157 io timer timeout
1158 close_terminal
1159 binary
1160 );
1161 127 @EXPORT_OK = ( @API, @FILTER_IMP, @FILTERS, qw( Win32_MODE ) );
1162 127 %EXPORT_TAGS = (
1163 'filter_imp' => \@FILTER_IMP,
1164 'all' => \@EXPORT_OK,
1165 'filters' => \@FILTERS,
1166 'api' => \@API,
1167 );
1168  
1169 }
1170  
1171 127 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
1172 127 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
1173 127 ▶use IPC::Run::Debug;
Subroutine BEGIN: called CC=1 SCAR=0.0
1174 127 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
1175 127 ▶use Fcntl;
Subroutine BEGIN: called CC=1 SCAR=0.0
1176 127 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
1177  
1178 BEGIN {
1179 127 ▶ if ( $] < 5.008 ) { require Symbol; }
Subroutine BEGIN: called CC=2 SCAR=9.2
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.008") 0 127 127
1180 }
1181 127 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
1182 127 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
1183 127 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
1184 127 require IPC::Run::IO;
1185 127 require IPC::Run::Timer;
1186  
1187 127 ▶use constant Win32_MODE => $^O =~ /os2|Win32/i;
Subroutine BEGIN: called CC=1 SCAR=0.0
1188  
1189 BEGIN {
1190 127 ▶ if (Win32_MODE) {
Subroutine BEGIN: called CC=6 SCAR=25.9
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 127 127
1191 0 ▶ eval "use IPC::Run::Win32Helper; 1;"
Branch: 1 branch
BranchTrueFalseTotal
eval "use IPC::Run::Win32Helper; 1;" or $@ and die or die "$!" 0 0 0
Condition0%0/5
eval "use IPC::Run::Win32Helper; 1;" or $@ and die
l!l&&r!l&&!r
000
$@ and die
!ll
00
MC/DC0%0/2
eval "use IPC::Run::Win32Helper; 1;" or $@ and die
eval "use IPC::Run::Win32Helper; 1;" $@
Truth table0%0/3
A or B
A= eval "use IPC::Run::Win32Helper; 1;"B= $@
ABresult
1X1
011
000
1192 or ( $@ && die )
1193 or die "$!";
1194 }
1195 else {
1196 127 ▶ eval "use File::Basename; 1;" or die $!;
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
eval "use File::Basename; 1;" or die $! 0 127 127
1197 }
1198 }
1199  
1200 sub input_avail();
1201 sub get_more_input();
1202  
1203 ###############################################################################
1204  
1205 ##
1206 ## Error constants, not too locale-dependent
1207 127 ▶use vars qw( $_EIO $_EAGAIN );
Subroutine BEGIN: called CC=1 SCAR=0.0
1208 127 ▶use Errno qw( EIO EAGAIN );
Subroutine BEGIN: called CC=1 SCAR=0.0
1209  
1210 BEGIN {
1211 127 ▶ local $!;
Subroutine BEGIN: called CC=1 SCAR=0.0
1212 127 $! = EIO;
1213 127 $_EIO = qr/^$!/;
1214 127 $! = EAGAIN;
1215 127 $_EAGAIN = qr/^$!/;
1216 }
1217  
1218 ##
1219 ## State machine states, set in $self->{STATE}
1220 ##
1221 ## These must be in ascending order numerically
1222 ##
1223 sub _newed() { 0 }
1224 sub _harnessed() { 1 }
1225 sub _finished() { 2 } ## _finished behave almost exactly like _harnessed
1226 sub _started() { 3 }
1227  
1228 ##
1229 ## Which fds have been opened in the parent. This may have extra fds, since
1230 ## we aren't all that rigorous about closing these off, but that's ok. This
1231 ## is used on Unixish OSs to close all fds in the child that aren't needed
1232 ## by that particular child.
1233 127 my %fds;
1234  
1235 ## There's a bit of hackery going on here.
1236 ##
1237 ## We want to have any code anywhere be able to emit
1238 ## debugging statements without knowing what harness the code is
1239 ## being called in/from, since we'd need to pass a harness around to
1240 ## everything.
1241 ##
1242 ## Thus, $cur_self was born.
1243  
1244 127 ▶use vars qw( $cur_self );
Subroutine BEGIN: called CC=1 SCAR=0.0
1245  
1246 sub _debug_fd {
1247 2093 ▶ return fileno STDERR unless defined $cur_self;
Subroutine _debug_fd: called CC=6 SCAR=27.7
Branch: 1 branch
BranchTrueFalseTotal
unless defined $IPC::Run::cur_self 0 2093 2093
1248  
1249 2093 ▶ if ( _debugging && !defined $cur_self->{DEBUG_FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging() and not defined $IPC::Run::cur_self->{"DEBUG_FD"}) 0 2093 2093
Condition33%1/3
&_debugging() and not defined $IPC::Run::cur_self->{"DEBUG_FD"}
!ll&&!rl&&r
209300
MC/DC0%0/2
&_debugging() and not defined $IPC::Run::cur_self->{"DEBUG_FD"}
&_debugging() not defined $IPC::Run::cur_self->{"DEBUG_FD"}
Truth table33%1/3
A and not(B)
A= &_debugging()B= not defined $IPC::Run::cur_self->{"DEBUG_FD"}
ABresult
0X0
100
111
1250 0 my $fd = select STDERR;
1251 0 $| = 1;
1252 0 select $fd;
1253 0 $cur_self->{DEBUG_FD} = POSIX::dup fileno STDERR;
1254 0 ▶ _debug("debugging fd is $cur_self->{DEBUG_FD}\n")
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
1255 if _debugging_details;
1256 }
1257  
1258 2093 ▶ return fileno STDERR unless defined $cur_self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $IPC::Run::cur_self->{"DEBUG_FD"} 2093 0 2093
1259  
1260 0 return $cur_self->{DEBUG_FD};
1261 }
1262  
1263 sub DESTROY {
1264 ## We absolutely do not want to do anything else here. We are likely
1265 ## to be in a child process and we don't want to do things like kill_kill
1266 ## ourself or cause other destruction.
1267 1562 ▶ my IPC::Run $self = shift;
Subroutine DESTROY: called CC=4 SCAR=13.9
1268 1562 ▶ POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"DEBUG_FD"} 0 1562 1562
1269 1562 $self->{DEBUG_FD} = undef;
1270  
1271 1562 for my $kid ( @{$self->{KIDS}} ) {
1272 1477 for my $op ( @{$kid->{OPS}} ) {
1273 2427 delete $op->{FILTERS};
1274 }
1275 }
1276 }
1277  
1278 ##
1279 ## Support routines (NOT METHODS)
1280 ##
1281 my %cmd_cache;
1282  
1283 sub _search_path {
1284 1371 ▶ my ($cmd_name) = @_;
Subroutine _search_path: called CC=38 SCAR=42.2
1285 1371 ▶ if ( File::Spec->file_name_is_absolute($cmd_name) && -x $cmd_name ) {
Branch: 1 branch
BranchTrueFalseTotal
if ("File::Spec"->file_name_is_absolute($cmd_name) and -x $cmd_name) 1212 159 1371
Condition66%2/3
"File::Spec"->file_name_is_absolute($cmd_name) and -x $cmd_name
!ll&&!rl&&r
15901212
MC/DC50%1/2
"File::Spec"->file_name_is_absolute($cmd_name) and -x $cmd_name
"File::Spec"->file_name_is_absolute($cmd_name) -x $cmd_name
Truth table66%2/3
A and B
A= "File::Spec"->file_name_is_absolute($cmd_name)B= -x $cmd_name
ABresult
0X0
100
111
1286 1212 ▶ _debug "'", $cmd_name, "' is absolute"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1212 1212
1287 if _debugging_details;
1288 1212 return $cmd_name;
1289 }
1290  
1291 159 ▶ my $dirsep = (
Branch: 3 branches
BranchTrueFalseTotal
&Win32_MODE() ? : 5 154 159
$^O =~ /MacOS/ ? : 0 154 154
$^O =~ /VMS/ ? : 0 154 154
1292 Win32_MODE ? '[/\\\\]'
1293 : $^O =~ /MacOS/ ? ':'
1294 : $^O =~ /VMS/ ? '[\[\]]'
1295 : '/'
1296 );
1297  
1298 159 ▶ if ( Win32_MODE
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE() and $cmd_name =~ /$dirsep/ and not $cmd_name =~ m[\.[^\\/\.]+$]) 5 154 159
Condition66%4/6
&Win32_MODE() and $cmd_name =~ /$dirsep/ and not $cmd_name =~ m[\.[^\\/\.]+$]
!ll&&!rl&&r
15405
&Win32_MODE() and $cmd_name =~ /$dirsep/
!ll&&!rl&&r
15405
MC/DC33%1/3
&Win32_MODE() and $cmd_name =~ /$dirsep/ and not $cmd_name =~ m[\.[^\\/\.]+$]
&Win32_MODE() $cmd_name =~ /$dirsep/ not $cmd_name =~ m[\.[^\\/\.]+$]
Truth table50%2/4
A and B and not(C)
A= &Win32_MODE()B= $cmd_name =~ /$dirsep/C= not $cmd_name =~ m[\.[^\\/\.]+$]
ABCresult
0XX0
10X0
1100
1111
1299 && ( $cmd_name =~ /$dirsep/ )
1300 && ( $cmd_name !~ m!\.[^\\/\.]+$! ) ) {
1301  
1302 5 ▶ _debug "no extension(.exe), checking ENV{PATHEXT}" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 5 5
1303 5 ▶ for ( split /;/, $ENV{PATHEXT} || ".COM;.BAT;.EXE" ) {
Condition50%1/2
$ENV{'PATHEXT'} || '.COM;.BAT;.EXE'
l!l
05
MC/DC0%0/1
$ENV{'PATHEXT'} || '.COM;.BAT;.EXE'
$ENV{'PATHEXT'}
Truth table50%1/2
A
A= $ENV{'PATHEXT'}
Aresult
11
00
1304 12 my $name = "$cmd_name$_";
1305 12 ▶ $cmd_name = $name, last if -f $name && -x _;
Branch: 1 branch
BranchTrueFalseTotal
if -f $name and -x _ 5 7 12
Condition66%2/3
-f $name and -x _
!ll&&!rl&&r
705
MC/DC50%1/2
-f $name and -x _
-f $name -x _
Truth table66%2/3
A and B
A= -f $nameB= -x _
ABresult
0X0
100
111
1306 }
1307 5 ▶ _debug "cmd_name is now '$cmd_name'" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 5 5
1308 }
1309  
1310 159 ▶ if ( $cmd_name =~ /($dirsep)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd_name =~ /($dirsep)/) 6 153 159
1311 6 ▶ _debug "'$cmd_name' contains '$1'" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 6 6
1312 6 ▶ croak "file not found: $cmd_name" unless -e $cmd_name;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $cmd_name 1 5 6
1313 5 ▶ croak "not a file: $cmd_name" unless -f $cmd_name;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $cmd_name 0 5 5
1314 5 ▶ croak "permission denied: $cmd_name" unless -x $cmd_name;
Branch: 1 branch
BranchTrueFalseTotal
unless -x $cmd_name 0 5 5
1315 5 return $cmd_name;
1316 }
1317  
1318 153 ▶ if ( exists $cmd_cache{$cmd_name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cmd_cache{$cmd_name}) 92 61 153
1319 92 ▶ _debug "'$cmd_name' found in cache: '$cmd_cache{$cmd_name}'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 92 92
1320 if _debugging;
1321 92 ▶ return $cmd_cache{$cmd_name} if -x $cmd_cache{$cmd_name};
Branch: 1 branch
BranchTrueFalseTotal
if -x $cmd_cache{$cmd_name} 92 0 92
1322 0 ▶ _debug "'$cmd_cache{$cmd_name}' no longer executable, searching..."
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
1323 if _debugging;
1324 0 delete $cmd_cache{$cmd_name};
1325 }
1326  
1327 61 my @searched_in;
1328  
1329 ## This next bit is Unix/Win32 specific, unfortunately.
1330 ## There's been some conversation about extending File::Spec to provide
1331 ## a universal interface to PATH, but I haven't seen it yet.
1332 61 ▶ my $re = Win32_MODE ? qr/;/ : qr/:/;
Branch: 1 branch
BranchTrueFalseTotal
&Win32_MODE() ? : 0 61 61
1333  
1334 LOOP:
1335 61 ▶ for ( split( $re, $ENV{PATH} || '', -1 ) ) {
Condition100%2/2
$ENV{'PATH'} || ''
l!l
601
MC/DC100%1/1
$ENV{'PATH'} || ''
$ENV{'PATH'}
Truth table100%2/2
A
A= $ENV{'PATH'}
Aresult
11
00
1336 420 ▶ $_ = "." unless length $_;
Branch: 1 branch
BranchTrueFalseTotal
unless length $_ 0 420 420
1337 420 push @searched_in, $_;
1338  
1339 420 my $prospect = File::Spec->catfile( $_, $cmd_name );
1340 420 my @prospects;
1341  
1342 @prospects =
1343 ( Win32_MODE && !( -f $prospect && -x _ ) )
1344 420 ▶ ? map "$prospect$_", split /;/, $ENV{PATHEXT} || ".COM;.BAT;.EXE"
Branch: 1 branch
BranchTrueFalseTotal
&Win32_MODE() && !(-f $prospect && -x _) ? : 0 420 420
Condition12%1/8
&Win32_MODE() and not -f $prospect && -x _
!ll&&!rl&&r
42000
-f $prospect && -x _
!ll&&!rl&&r
000
$ENV{'PATHEXT'} || '.COM;.BAT;.EXE'
l!l
00
MC/DC0%0/3
&Win32_MODE() and not -f $prospect && -x _
&Win32_MODE() -f $prospect -x _
MC/DC0%0/1
$ENV{'PATHEXT'} || '.COM;.BAT;.EXE'
$ENV{'PATHEXT'}
Truth table25%1/4
A and not(B && C)
A= &Win32_MODE()B= -f $prospectC= -x _
ABCresult
0XX0
1110
10X1
1101
Truth table0%0/2
A
A= $ENV{'PATHEXT'}
Aresult
11
00
1345 : ($prospect);
1346  
1347 420 for my $found (@prospects) {
1348 420 ▶ if ( -f $found && -x _ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $found and -x _) 60 360 420
Condition66%2/3
-f $found and -x _
!ll&&!rl&&r
360060
MC/DC50%1/2
-f $found and -x _
-f $found -x _
Truth table66%2/3
A and B
A= -f $foundB= -x _
ABresult
0X0
100
111
1349 60 $cmd_cache{$cmd_name} = $found;
1350 60 last LOOP;
1351 }
1352 }
1353 }
1354  
1355 61 ▶ if ( exists $cmd_cache{$cmd_name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cmd_cache{$cmd_name}) 60 1 61
1356 60 ▶ _debug "'", $cmd_name, "' added to cache: '", $cmd_cache{$cmd_name}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 60 60
1357 if _debugging_details;
1358 60 return $cmd_cache{$cmd_name};
1359 }
1360  
1361 1 croak "Command '$cmd_name' not found in " . join( ", ", @searched_in );
1362 }
1363  
1364 # Translate a command or CODE reference (a $kid->{VAL}) to a list of strings
1365 # suitable for passing to _debug().
1366 sub _debugstrings {
1367 0 ▶ my $operand = shift;
Subroutine _debugstrings: not called CC=7 SCAR=40.3
1368 0 ▶ if ( !defined $operand ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $operand) 0 0 0
1369 0 return '<undef>';
1370 }
1371  
1372 0 my $ref = ref $operand;
1373 0 ▶ if ( !$ref ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not $ref) { } 0 0 0
elsif ($ref eq 'ARRAY') { } 0 0 0
elsif (UNIVERSAL::isa($operand, 'IPC::Run::Win32Process')) { } 0 0 0
1374 0 ▶ return length $operand < 50
Branch: 1 branch
BranchTrueFalseTotal
length $operand < 50 ? : 0 0 0
1375 ? "'$operand'"
1376 : join( '', "'", substr( $operand, 0, 10 ), "...'" );
1377 }
1378 elsif ( $ref eq 'ARRAY' ) {
1379 return (
1380 0 ▶ '[ ',
Branch: 1 branch
BranchTrueFalseTotal
/[^\w.-]/ ? : 0 0 0
1381 join( " ", map /[^\w.-]/ ? "'$_'" : $_, @$operand ),
1382 ' ]'
1383 );
1384 }
1385 elsif ( UNIVERSAL::isa( $operand, 'IPC::Run::Win32Process' ) ) {
1386 0 return "$operand";
1387 }
1388 0 return $ref;
1389 }
1390  
1391 7145 ▶sub _empty($) { !( defined $_[0] && length $_[0] ) }
Subroutine _empty: called CC=2 SCAR=6.9
Condition100%3/3
defined $_[0] && length $_[0]
!ll&&!rl&&r
19112445710
MC/DC100%2/2
defined $_[0] && length $_[0]
defined $_[0] length $_[0]
Truth table100%3/3
A && B
A= defined $_[0]B= length $_[0]
ABresult
0X0
100
111
1392  
1393 ## 'safe' versions of otherwise fun things to do. See also IPC::Run::Win32Helper.
1394 sub _close {
1395 7170 ▶ confess 'undef' unless defined $_[0];
Subroutine _close: called CC=13 SCAR=41.7
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 7170 7170
1396 7170 ▶ my $fd = $_[0] =~ /^\d+$/ ? $_[0] : fileno $_[0];
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /^\d+$/ ? : 7170 0 7170
1397 7170 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) 0 7170 7170
1398  
1399 # Perl close() or POSIX::close() on the read end of a pipe hangs if
1400 # another process is in a read attempt on the same pipe
1401 # (https://github.com/Perl/perl5/issues/19963). Since IPC::Run creates
1402 # pipes and shares them with user-defined kids, it's affected. Work
1403 # around that by first using dup2() to replace the FD with a non-pipe.
1404 # Unfortunately, for socket FDs, dup2() closes the SOCKET with
1405 # CloseHandle(). CloseHandle() documentation leaves its behavior
1406 # undefined for sockets. However, tests on Windows Server 2022 did not
1407 # leak memory, leak ports, or reveal any other obvious trouble.
1408 #
1409 # No failure here is fatal. (_close() has worked that way, either due
1410 # to a principle or just due to a history of callers passing closed
1411 # FDs.) croak() on EMFILE would be a bad user experience. Better to
1412 # proceed and hope that $fd is not a being-read pipe.
1413 #
1414 # Since start() and other user-facing methods _close() many FDs, we
1415 # could optimize this by opening and closing the non-pipe FD just once
1416 # per method call. The overhead of this simple approach was in the
1417 # noise, however.
1418 0 my $nul_fd = POSIX::open 'NUL';
1419 0 ▶ if ( !defined $nul_fd ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $nul_fd) { } 0 0 0
1420 0 ▶ _debug "open( NUL ) = ERROR $!" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
1421 }
1422 else {
1423 0 my $r = POSIX::dup2( $nul_fd, $fd );
1424 0 ▶ _debug "dup2( $nul_fd, $fd ) = ERROR $!"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() and not defined $r 0 0 0
Condition0%0/3
&_debugging_details() and not defined $r
!ll&&!rl&&r
000
MC/DC0%0/2
&_debugging_details() and not defined $r
&_debugging_details() not defined $r
Truth table0%0/3
A and not(B)
A= &_debugging_details()B= not defined $r
ABresult
0X0
100
111
1425 if _debugging_details && !defined $r;
1426 0 $r = POSIX::close $nul_fd;
1427 0 ▶ _debug "close( $nul_fd (NUL) ) = ERROR $!"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() and not defined $r 0 0 0
Condition0%0/3
&_debugging_details() and not defined $r
!ll&&!rl&&r
000
MC/DC0%0/2
&_debugging_details() and not defined $r
&_debugging_details() not defined $r
Truth table0%0/3
A and not(B)
A= &_debugging_details()B= not defined $r
ABresult
0X0
100
111
1428 if _debugging_details && !defined $r;
1429 }
1430 }
1431 7170 my $r = POSIX::close $fd;
1432 7170 ▶ $r = $r ? '' : " ERROR $!";
Branch: 1 branch
BranchTrueFalseTotal
$r ? : 7151 19 7170
1433 7170 delete $fds{$fd};
1434 7170 ▶ _debug "close( $fd ) = " . ( $r || 0 ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 7170 7170
Condition0%0/2
$r || 0
l!l
00
MC/DC0%0/1
$r || 0
$r
Truth table0%0/2
A
A= $r
Aresult
11
00
1435 }
1436  
1437 sub _dup {
1438 1290 ▶ confess 'undef' unless defined $_[0];
Subroutine _dup: called CC=5 SCAR=17.0
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 1290 1290
1439 1290 my $r = POSIX::dup( $_[0] );
1440 1290 ▶ croak "$!: dup( $_[0] )" unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 0 1290 1290
1441 1290 ▶ $r = 0 if $r eq '0 but true';
Branch: 1 branch
BranchTrueFalseTotal
if $r eq "0 but true" 0 1290 1290
1442 1290 ▶ _debug "dup( $_[0] ) = $r" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1290 1290
1443 1290 $fds{$r} = {};
1444 1290 return $r;
1445 }
1446  
1447 sub _dup2_rudely {
1448 202 ▶ confess 'undef' unless defined $_[0] && defined $_[1];
Subroutine _dup2_rudely: called CC=6 SCAR=19.1
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and defined $_[1] 0 202 202
Condition33%1/3
defined $_[0] and defined $_[1]
!ll&&!rl&&r
00202
MC/DC0%0/2
defined $_[0] and defined $_[1]
defined $_[0] defined $_[1]
Truth table33%1/3
A and B
A= defined $_[0]B= defined $_[1]
ABresult
0X0
100
111
1449 202 my $r = POSIX::dup2( $_[0], $_[1] );
1450 202 ▶ croak "$!: dup2( $_[0], $_[1] )" unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 0 202 202
1451 202 ▶ $r = 0 if $r eq '0 but true';
Branch: 1 branch
BranchTrueFalseTotal
if $r eq "0 but true" 67 135 202
1452 202 ▶ _debug "dup2( $_[0], $_[1] ) = $r" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 202 202
1453 202 $fds{$r} = {};
1454 202 return $r;
1455 }
1456  
1457 sub _exec {
1458 99 ▶ confess 'undef passed' if grep !defined, @_;
Subroutine _exec: called CC=3 SCAR=11.4
Branch: 1 branch
BranchTrueFalseTotal
if grep((!defined($_)), @_) 0 99 99
1459  
1460 # exec @_ or croak "$!: exec( " . join( ', ', @_ ) . " )";
1461 99 ▶ _debug 'exec()ing ', join " ", map "'$_'", @_ if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 99 99
1462  
1463 # {
1464 ## Commented out since we don't call this on Win32.
1465 # # This works around the bug where 5.6.1 complains
1466 # # "Can't exec ...: No error" after an exec on NT, where
1467 # # exec() is simulated and actually returns in Perl's C
1468 # # code, though Perl's &exec does not...
1469 # no warnings "exec";
1470 #
1471 # # Just in case the no warnings workaround
1472 # # stops being a workaround, we don't want
1473 # # old values of $! causing spurious strerr()
1474 # # messages to appear in the "Can't exec" message
1475 # undef $!;
1476 99 exec { $_[0] } @_;
1477  
1478 # }
1479 # croak "$!: exec( " . join( ', ', map "'$_'", @_ ) . " )";
1480 ## Fall through so $! can be reported to parent.
1481 }
1482  
1483 sub _sysopen {
1484 228 ▶ confess 'undef' unless defined $_[0] && defined $_[1];
Subroutine _sysopen: called CC=6 SCAR=19.1
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and defined $_[1] 0 228 228
Condition33%1/3
defined $_[0] and defined $_[1]
!ll&&!rl&&r
00228
MC/DC0%0/2
defined $_[0] and defined $_[1]
defined $_[0] defined $_[1]
Truth table33%1/3
A and B
A= defined $_[0]B= defined $_[1]
ABresult
0X0
100
111
1485 228 ▶ _debug sprintf( "O_RDONLY=0x%02x ", O_RDONLY ),
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 228 228
1486 sprintf( "O_WRONLY=0x%02x ", O_WRONLY ),
1487 sprintf( "O_RDWR=0x%02x ", O_RDWR ),
1488 sprintf( "O_TRUNC=0x%02x ", O_TRUNC ),
1489 sprintf( "O_CREAT=0x%02x ", O_CREAT ),
1490 sprintf( "O_APPEND=0x%02x ", O_APPEND ),
1491 if _debugging_details;
1492 228 my $r = POSIX::open( $_[0], $_[1], 0666 );
1493 228 ▶ croak "$!: open( $_[0], ", sprintf( "0x%03x", $_[1] ), " )" unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 19 209 228
1494 209 ▶ _debug "open( $_[0], ", sprintf( "0x%03x", $_[1] ), " ) = $r"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 209 209
1495 if _debugging_data;
1496 209 $fds{$r} = {};
1497 209 return $r;
1498 }
1499  
1500 sub _pipe {
1501 ## Normal, blocking write for pipes that we read and the child writes,
1502 ## since most children expect writes to stdout to block rather than
1503 ## do a partial write.
1504 2911 ▶ my ( $r, $w ) = POSIX::pipe;
Subroutine _pipe: called CC=3 SCAR=11.3
1505 2911 ▶ croak "$!: pipe()" unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 0 2911 2911
1506 2911 ▶ _debug "pipe() = ( $r, $w ) " if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2911 2911
1507 2911 @fds{$r, $w} = ( {}, {} );
1508 2911 return ( $r, $w );
1509 }
1510  
1511 sub _pipe_nb {
1512 ## For pipes that we write, unblock the write side, so we can fill a buffer
1513 ## and continue to select().
1514 ## Contributed by Borislav Deianov <borislav@ensim.com>, with minor
1515 ## bugfix on fcntl result by me.
1516 643 ▶ local ( *R, *W );
Subroutine _pipe_nb: called CC=7 SCAR=20.5
1517 643 my $f = pipe( R, W );
1518 643 ▶ croak "$!: pipe()" unless defined $f;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $f 0 643 643
1519 643 my ( $r, $w ) = ( fileno R, fileno W );
1520 643 ▶ _debug "pipe_nb pipe() = ( $r, $w )" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 643 643
1521 643 ▶ unless (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&Win32_MODE()) 643 0 643
1522 ## POSIX::fcntl doesn't take fd numbers, so gotta use Perl's and
1523 ## then _dup the originals (which get closed on leaving this block)
1524 643 my $fres = fcntl( W, &F_SETFL, O_WRONLY | O_NONBLOCK );
1525 643 ▶ croak "$!: fcntl( $w, F_SETFL, O_NONBLOCK )" unless $fres;
Branch: 1 branch
BranchTrueFalseTotal
unless $fres 0 643 643
1526 643 ▶ _debug "fcntl( $w, F_SETFL, O_NONBLOCK )" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 643 643
1527 }
1528 643 ( $r, $w ) = ( _dup($r), _dup($w) );
1529 643 ▶ _debug "pipe_nb() = ( $r, $w )" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 643 643
1530 643 return ( $r, $w );
1531 }
1532  
1533 sub _pty {
1534 14 ▶ require IO::Pty;
Subroutine _pty: called CC=4 SCAR=14.2
1535 14 my $pty = IO::Pty->new();
1536 14 ▶ croak "$!: pty ()" unless $pty;
Branch: 1 branch
BranchTrueFalseTotal
unless $pty 0 14 14
1537 14 $pty->autoflush();
1538 14 ▶ $pty->blocking(0) or croak "$!: pty->blocking ( 0 )";
Branch: 1 branch
BranchTrueFalseTotal
$pty->blocking(0) or croak("$!: pty->blocking ( 0 )") 0 14 14
1539 14 ▶ _debug "pty() = ( ", $pty->fileno, ", ", $pty->slave->fileno, " )"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 14 14
1540 if _debugging_details;
1541 14 @fds{ $pty->fileno, $pty->slave->fileno } = ( {}, {} );
1542 14 return $pty;
1543 }
1544  
1545 sub _read {
1546 3972 ▶ confess 'undef' unless defined $_[0];
Subroutine _read: called CC=7 SCAR=19.6
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 3972 3972
1547 3972 my $s = '';
1548 3972 my $r;
1549 do {
1550 3973 $r = POSIX::read( $_[0], $s, 10_000 );
1551 3972 ▶ } while ( !defined($r) && $!{EINTR} );
Branch: 1 branch
BranchTrueFalseTotal
not defined $r and $!{"EINTR"} and do { do { $r = POSIX::read($_[0], $s, 10000) } } 1 3972 3973
Condition100%3/3
not defined $r and $!{"EINTR"}
!ll&&!rl&&r
396661
MC/DC100%2/2
not defined $r and $!{"EINTR"}
not defined $r $!{"EINTR"}
Truth table100%3/3
not(A) and B
A= not defined $rB= $!{"EINTR"}
ABresult
0X0
100
111
1552 3972 ▶ croak "$!: read( $_[0] )" unless defined($r);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 6 3966 3972
1553 3966 ▶ $r ||= 0;
Condition50%1/2
$r ||= 0
l!l
39660
MC/DC0%0/1
$r ||= 0
$r
Truth table50%1/2
A
A= $r
Aresult
11
00
1554 3966 ▶ _debug "read( $_[0] ) = $r chars '$s'" if _debugging_data;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 3966 3966
1555 3966 return $s;
1556 }
1557  
1558 ## A METHOD, not a function.
1559 sub _spawn {
1560 1450 ▶ my IPC::Run $self = shift;
Subroutine _spawn: called CC=13 SCAR=30.7
1561 1450 my ($kid) = @_;
1562  
1563 croak "Can't spawn IPC::Run::Win32Process except on Win32"
1564 1450 ▶ if UNIVERSAL::isa( $kid->{VAL}, 'IPC::Run::Win32Process' );
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($kid->{"VAL"}, "IPC::Run::Win32Process") 0 1450 1450
1565  
1566 1450 ▶ _debug "opening sync pipe ", $kid->{PID} if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1450 1450
1567 1450 my $sync_reader_fd;
1568 1450 ( $sync_reader_fd, $self->{SYNC_WRITER_FD} ) = _pipe;
1569 1450 $kid->{PID} = fork();
1570 1450 ▶ croak "$! during fork" unless defined $kid->{PID};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kid->{"PID"} 0 1450 1450
1571  
1572 1450 ▶ unless ( $kid->{PID} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($kid->{"PID"}) 101 1349 1450
1573 101 ▶ if ( $self->{_sigusr1_after_fork} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_sigusr1_after_fork"}) 0 101 101
1574  
1575 # sleep 10ms to improve chance of parent starting read() before it
1576 # handles the signal we're about to send.
1577 0 select undef, undef, undef, 0.01;
1578 0 kill 'USR1', getppid;
1579 }
1580 ## _do_kid_and_exit closes sync_reader_fd since it closes all unwanted and
1581 ## unloved fds.
1582 101 $self->_do_kid_and_exit($kid);
1583 }
1584 1349 ▶ _debug "fork() = ", $kid->{PID} if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1349 1349
1585  
1586 ## Wait for kid to get to its exec() and see if it fails.
1587 1349 _close $self->{SYNC_WRITER_FD};
1588 1349 my $sync_pulse = _read $sync_reader_fd;
1589 1349 _close $sync_reader_fd;
1590  
1591 1349 ▶ if ( !defined $sync_pulse || length $sync_pulse ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $sync_pulse or length $sync_pulse) 2 1347 1349
Condition66%2/3
not defined $sync_pulse or length $sync_pulse
l!l&&r!l&&!r
021347
MC/DC50%1/2
not defined $sync_pulse or length $sync_pulse
not defined $sync_pulse length $sync_pulse
Truth table66%2/3
not(A) or B
A= not defined $sync_pulseB= length $sync_pulse
ABresult
1X1
011
000
1592 2 ▶ if ( waitpid( $kid->{PID}, 0 ) >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (waitpid($kid->{'PID'}, 0) >= 0) { } 2 0 2
1593 2 $kid->{RESULT} = $?;
1594 }
1595 else {
1596 0 $kid->{RESULT} = -1;
1597 }
1598 2 ▶ $sync_pulse = "error reading synchronization pipe for $kid->{NUM}, pid $kid->{PID}"
Branch: 1 branch
BranchTrueFalseTotal
unless length $sync_pulse 0 2 2
1599 unless length $sync_pulse;
1600 2 croak $sync_pulse;
1601 }
1602 1347 return $kid->{PID};
1603  
1604 ## Wait for pty to get set up. This is a hack until we get synchronous
1605 ## selects.
1606 0 ▶ if ( keys %{ $self->{PTYS} } && $IO::Pty::VERSION < 0.9 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{"PTYS"};} and $IO::Pty::VERSION < "0.9") 0 0 0
Condition0%0/3
keys %{$$self{"PTYS"};} and $IO::Pty::VERSION < "0.9"
!ll&&!rl&&r
000
MC/DC0%0/2
keys %{$$self{"PTYS"};} and $IO::Pty::VERSION < "0.9"
keys %{$$self{"PTYS"};} $IO::Pty::VERSION < "0.9"
Truth table0%0/3
A and B
A= keys %{$$self{"PTYS"};}B= $IO::Pty::VERSION < "0.9"
ABresult
0X0
100
111
1607 0 _debug "sleeping to give pty a chance to init, will fix when newer IO::Pty arrives.";
1608 0 sleep 1;
1609 }
1610 }
1611  
1612 sub _write {
1613 394 ▶ confess 'undef' unless defined $_[0] && defined $_[1];
Subroutine _write: called CC=5 SCAR=18.1
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and defined $_[1] 0 394 394
Condition33%1/3
defined $_[0] and defined $_[1]
!ll&&!rl&&r
00394
MC/DC0%0/2
defined $_[0] and defined $_[1]
defined $_[0] defined $_[1]
Truth table33%1/3
A and B
A= defined $_[0]B= defined $_[1]
ABresult
0X0
100
111
1614 394 my $r = POSIX::write( $_[0], $_[1], length $_[1] );
1615 394 ▶ croak "$!: write( $_[0], '$_[1]' )" unless $r;
Branch: 1 branch
BranchTrueFalseTotal
unless $r 0 394 394
1616 394 ▶ _debug "write( $_[0], '$_[1]' ) = $r" if _debugging_data;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 394 394
1617 394 return $r;
1618 }
1619  
1620 =pod
1621  
1622 =over
1623  
1624 =item run
1625  
1626 Run takes a harness or harness specification and runs it, pumping
1627 all input to the child(ren), closing the input pipes when no more
1628 input is available, collecting all output that arrives, until the
1629 pipes delivering output are closed, then waiting for the children to
1630 exit and reaping their result codes.
1631  
1632 You may think of C<run( ... )> as being like
1633  
1634 start( ... )->finish();
1635  
1636 , though there is one subtle difference: run() does not
1637 set \$input_scalars to '' like finish() does. If an exception is thrown
1638 from run(), all children will be killed off "gently", and then "annihilated"
1639 if they do not go gently (in to that dark night. sorry).
1640  
1641 If any exceptions are thrown, this does a L</kill_kill> before propagating
1642 them.
1643  
1644 =cut
1645  
1646 127 ▶use vars qw( $in_run ); ## No, not Enron;)
Subroutine BEGIN: called CC=1 SCAR=0.0
1647  
1648 sub run {
1649 1433 ▶ local $in_run = 1; ## Allow run()-only optimizations.
Subroutine run: called CC=2 SCAR=6.9
Pod documented
1650 1433 my IPC::Run $self = start(@_);
1651 1222 my $r = eval {
1652 1222 $self->{clear_ins} = 0;
1653 1222 $self->finish;
1654 };
1655 1222 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 1221 1222
1656 1 my $x = $@;
1657 1 $self->kill_kill;
1658 1 die $x;
1659 }
1660 1221 return $r;
1661 }
1662  
1663 =pod
1664  
1665 =item signal
1666  
1667 ## To send it a specific signal by name ("USR1"):
1668 signal $h, "USR1";
1669 $h->signal ( "USR1" );
1670  
1671 If $signal is provided and defined, sends a signal to all child processes. Try
1672 not to send numeric signals, use C<"KILL"> instead of C<9>, for instance.
1673 Numeric signals aren't portable.
1674  
1675 Throws an exception if $signal is undef.
1676  
1677 This will I<not> clean up the harness, C<finish> it if you kill it.
1678  
1679 Normally TERM kills a process gracefully (this is what the command line utility
1680 C<kill> does by default), INT is sent by one of the keys C<^C>, C<Backspace> or
1681 C<E<lt>DelE<gt>>, and C<QUIT> is used to kill a process and make it coredump.
1682  
1683 The C<HUP> signal is often used to get a process to "restart", rereading
1684 config files, and C<USR1> and C<USR2> for really application-specific things.
1685  
1686 Often, running C<kill -l> (that's a lower case "L") on the command line will
1687 list the signals present on your operating system.
1688  
1689 B<WARNING>: The signal subsystem is not at all portable. We *may* offer
1690 to simulate C<TERM> and C<KILL> on some operating systems, submit code
1691 to me if you want this.
1692  
1693 B<WARNING 2>: Up to and including perl v5.6.1, doing almost anything in a
1694 signal handler could be dangerous. The most safe code avoids all
1695 mallocs and system calls, usually by preallocating a flag before
1696 entering the signal handler, altering the flag's value in the
1697 handler, and responding to the changed value in the main system:
1698  
1699 my $got_usr1 = 0;
1700 sub usr1_handler { ++$got_signal }
1701  
1702 $SIG{USR1} = \&usr1_handler;
1703 while () { sleep 1; print "GOT IT" while $got_usr1--; }
1704  
1705 Even this approach is perilous if ++ and -- aren't atomic on your system
1706 (I've never heard of this on any modern CPU large enough to run perl).
1707  
1708 =cut
1709  
1710 sub signal {
1711 15 ▶ my IPC::Run $self = shift;
Subroutine signal: called CC=9 SCAR=26.5
Pod documented
1712  
1713 15 local $cur_self = $self;
1714  
1715 15 ▶ $self->_kill_kill_kill_pussycat_kill unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 15 15
1716  
1717 15 ▶ Carp::cluck "Ignoring extra parameters passed to kill()" if @_ > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 0 15 15
1718  
1719 15 my ($signal) = @_;
1720 15 ▶ croak "Undefined signal passed to signal" unless defined $signal;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $signal 0 15 15
1721 15 ▶ for ( grep $_->{PID} && !defined $_->{RESULT}, @{ $self->{KIDS} } ) {
Condition33%1/3
$_->{'PID'} && !defined($_->{'RESULT'})
!ll&&!rl&&r
0015
MC/DC0%0/2
$_->{'PID'} && !defined($_->{'RESULT'})
$_->{'PID'} !defined($_->{'RESULT'})
Truth table33%1/3
A && not(B)
A= $_->{'PID'}B= !defined($_->{'RESULT'})
ABresult
0X0
100
111
1722 15 ▶ _debug "sending $signal to $_->{PID}"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 15 15
1723 if _debugging;
1724 kill $signal, $_->{PID}
1725 15 ▶ or _debugging && _debug "$! sending $signal to $_->{PID}";
Branch: 1 branch
BranchTrueFalseTotal
kill $signal, $_->{"PID"} or &_debugging() and _debug(qq[$! sending $signal to $_->{"PID"}]) 0 15 15
Condition16%1/6
kill($signal, $_->{'PID'}) || &_debugging() && _debug("$! sending $signal to $_->{'PID'}")
l!l&&r!l&&!r
1500
&_debugging() and _debug(qq[$! sending $signal to $_->{"PID"}])
!ll&&!rl&&r
000
MC/DC0%0/3
kill($signal, $_->{'PID'}) || &_debugging() && _debug("$! sending $signal to $_->{'PID'}")
kill($signal, $_->{'PID'}) &_debugging() _debug(qq[$! sending $signal to $_->{"PID"}])
Truth table0%0/4
A || B and C
A= kill($signal, $_->{'PID'})B= &_debugging()C= _debug(qq[$! sending $signal to $_->{"PID"}])
ABCresult
1XX1
0111
00X0
0100
1726 }
1727  
1728 15 return;
1729 }
1730  
1731 =pod
1732  
1733 =item kill_kill
1734  
1735 ## To kill off a process:
1736 $h->kill_kill;
1737 kill_kill $h;
1738  
1739 ## To specify the grace period other than 30 seconds:
1740 kill_kill $h, grace => 5;
1741  
1742 ## To send QUIT instead of KILL if a process refuses to die:
1743 kill_kill $h, coup_d_grace => "QUIT";
1744  
1745 Sends a C<TERM>, waits for all children to exit for up to 30 seconds, then
1746 sends a C<KILL> to any that survived the C<TERM>.
1747  
1748 Will wait for up to 30 more seconds for the OS to successfully C<KILL> the
1749 processes.
1750  
1751 The 30 seconds may be overridden by setting the C<grace> option, this
1752 overrides both timers.
1753  
1754 The harness is then cleaned up.
1755  
1756 The doubled name indicates that this function may kill again and avoids
1757 colliding with the core Perl C<kill> function.
1758  
1759 Returns undef if the C<TERM> was sufficient, or a 1 if C<KILL> was
1760 required. Throws an exception if C<KILL> did not permit the children
1761 to be reaped.
1762  
1763 B<NOTE>: The grace period is actually up to 1 second longer than that
1764 given. This is because the granularity of C<time> is 1 second. Let me
1765 know if you need finer granularity, we can leverage Time::HiRes here.
1766  
1767 B<Win32>: Win32 does not know how to send real signals, so C<TERM> is
1768 a full-force kill on Win32. Thus all talk of grace periods, etc. do
1769 not apply to Win32.
1770  
1771 =cut
1772  
1773 sub kill_kill {
1774 9 ▶ my IPC::Run $self = shift;
Subroutine kill_kill: called CC=11 SCAR=24.2
Pod documented
1775  
1776 9 my %options = @_;
1777 9 my $grace = $options{grace};
1778 9 ▶ $grace = 30 unless defined $grace;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $grace 8 1 9
1779 9 ++$grace; ## Make grace time a _minimum_
1780  
1781 9 my $coup_d_grace = $options{coup_d_grace};
1782 9 ▶ $coup_d_grace = "KILL" unless defined $coup_d_grace;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $coup_d_grace 9 0 9
1783  
1784 9 delete $options{$_} for qw( grace coup_d_grace );
1785 9 ▶ Carp::cluck "Ignoring unknown options for kill_kill: ",
Branch: 1 branch
BranchTrueFalseTotal
if keys %options 0 9 9
1786 join " ", keys %options
1787 if keys %options;
1788  
1789 9 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 9 9
1790 # immediate brutal death for Win32
1791 # TERM has unfortunate side-effects
1792 0 $self->signal("KILL")
1793 }
1794 else {
1795 9 $self->signal("TERM");
1796 }
1797  
1798 9 my $quitting_time = time + $grace;
1799 9 my $delay = 0.01;
1800 9 my $accum_delay;
1801  
1802 my $have_killed_before;
1803  
1804 9 while () {
1805 ## delay first to yield to other processes
1806 17 select undef, undef, undef, $delay;
1807 17 $accum_delay += $delay;
1808  
1809 17 $self->reap_nb;
1810 17 ▶ last unless $self->_running_kids;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_running_kids 9 8 17
1811  
1812 8 ▶ if ( $accum_delay >= $grace * 0.8 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($accum_delay >= $grace * "0.8") 1 7 8
1813 ## No point in checking until delay has grown some.
1814 1 ▶ if ( time >= $quitting_time ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time >= $quitting_time) 1 0 1
1815 1 ▶ if ( !$have_killed_before ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($have_killed_before) 1 0 1
1816 1 $self->signal($coup_d_grace);
1817 1 $have_killed_before = 1;
1818 1 $quitting_time += $grace;
1819 1 $delay = 0.01;
1820 1 $accum_delay = 0;
1821 1 next;
1822 }
1823 0 croak "Unable to reap all children, even after KILLing them";
1824 }
1825 }
1826  
1827 7 $delay *= 2;
1828 7 ▶ $delay = 0.5 if $delay >= 0.5;
Branch: 1 branch
BranchTrueFalseTotal
if $delay >= "0.5" 2 5 7
1829 }
1830  
1831 9 $self->_cleanup;
1832 9 return $have_killed_before;
1833 }
1834  
1835 =pod
1836  
1837 =item harness
1838  
1839 Takes a harness specification and returns a harness. This harness is
1840 blessed in to IPC::Run, allowing you to use method call syntax for
1841 run(), start(), et al if you like.
1842  
1843 harness() is provided so that you can pre-build harnesses if you
1844 would like to, but it's not required..
1845  
1846 You may proceed to run(), start() or pump() after calling harness() (pump()
1847 calls start() if need be). Alternatively, you may pass your
1848 harness specification to run() or start() and let them harness() for
1849 you. You can't pass harness specifications to pump(), though.
1850  
1851 =cut
1852  
1853 ##
1854 ## Notes: I've avoided handling a scalar that doesn't look like an
1855 ## opcode as a here document or as a filename, though I could DWIM
1856 ## those. I'm not sure that the advantages outweigh the danger when
1857 ## the DWIMer guesses wrong.
1858 ##
1859 ## TODO: allow user to spec default shell. Hmm, globally, in the
1860 ## lexical scope hash, or per instance? 'Course they can do that
1861 ## now by using a [...] to hold the command.
1862 ##
1863 127 my $harness_id = 0;
1864  
1865 sub harness {
1866 1700 ▶ my $options;
Subroutine harness: called CC=114 SCAR=50.4
Pod documented
1867 1700 ▶ if ( @_ && ref $_[-1] eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ref $_[-1] eq "HASH") 0 1700 1700
Condition66%2/3
@_ and ref $_[-1] eq "HASH"
!ll&&!rl&&r
10415960
MC/DC0%0/2
@_ and ref $_[-1] eq "HASH"
@_ ref $_[-1] eq "HASH"
Truth table66%2/3
A and B
A= @_B= ref $_[-1] eq "HASH"
ABresult
0X0
100
111
1868 0 $options = pop;
1869 0 require Data::Dumper;
1870 0 carp "Passing in options as a hash is deprecated:\n", Data::Dumper::Dumper($options);
1871 }
1872  
1873 # local $IPC::Run::debug = $options->{debug}
1874 # if $options && defined $options->{debug};
1875  
1876 1700 my @args;
1877 1700 ▶ if ( @_ == 1 && !ref $_[0] ) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ == 1 and not ref $_[0]) { } 93 1607 1700
elsif (@_ > 1 and not grep(ref($_), @_)) { } 89 1518 1607
Condition100%3/3
@_ == 1 and not ref $_[0]
!ll&&!rl&&r
15941393
MC/DC100%2/2
@_ == 1 and not ref $_[0]
@_ == 1 not ref $_[0]
Truth table100%3/3
A and not(B)
A= @_ == 1B= not ref $_[0]
ABresult
0X0
100
111
1878 93 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 93 93
1879 0 ▶ my $command = $ENV{ComSpec} || 'cmd';
Condition0%0/2
$ENV{'ComSpec'} || 'cmd'
l!l
00
MC/DC0%0/1
$ENV{'ComSpec'} || 'cmd'
$ENV{'ComSpec'}
Truth table0%0/2
A
A= $ENV{'ComSpec'}
Aresult
11
00
1880 0 @args = ( [ $command, '/c', win32_parse_cmd_line $_[0] ] );
1881 }
1882 else {
1883 93 @args = ( [ qw( sh -c ), @_ ] );
1884 }
1885 }
1886 ▶ elsif ( @_ > 1 && !grep ref $_, @_ ) {
Condition100%3/3
@_ > 1 and not grep(ref($_), @_)
!ll&&!rl&&r
117140189
MC/DC100%2/2
@_ > 1 and not grep(ref($_), @_)
@_ > 1 not grep(ref($_), @_)
Truth table100%3/3
A and not(B)
A= @_ > 1B= not grep(ref($_), @_)
ABresult
0X0
100
111
1887 89 @args = ( [@_] );
1888 }
1889 else {
1890 1518 ▶ @args = map { !defined $_ ? bless(\$_, 'IPC::Run::Undef') : $_ } @_;
Branch: 1 branch
BranchTrueFalseTotal
!defined($_) ? : 2 7505 7507
1891 }
1892  
1893 1700 my @errs; # Accum errors, emit them when done.
1894  
1895 my $succinct; # set if no redir ops are required yet. Cleared
1896 # if an op is seen.
1897  
1898 1700 my $cur_kid; # references kid or handle being parsed
1899 1700 my $next_kid_close_stdin = 0;
1900  
1901 1700 my $assumed_fd = 0; # fd to assume in succinct mode (no redir ops)
1902 1700 my $handle_num = 0; # 1... is which handle we're parsing
1903  
1904 1700 my IPC::Run $self = bless {}, __PACKAGE__;
1905  
1906 1700 local $cur_self = $self;
1907  
1908 1700 $self->{ID} = ++$harness_id;
1909 1700 $self->{IOS} = [];
1910 1700 $self->{KIDS} = [];
1911 1700 $self->{PIPES} = [];
1912 1700 $self->{PTYS} = {};
1913 1700 $self->{STATE} = _newed;
1914  
1915 1700 ▶ if ($options) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options) 0 1700 1700
1916 0 $self->{$_} = $options->{$_} for keys %$options;
1917 }
1918  
1919 1700 ▶ _debug "****** harnessing *****" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 1700 1700
1920  
1921 1700 my $first_parse;
1922 1700 local $_;
1923 1700 my $arg_count = @args;
1924 1700 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 5403 1700 7103
1925 5403 for ( shift @args ) {
1926 5403 eval {
1927 5403 $first_parse = 1;
1928 5403 ▶ _debug( "parsing ", _debugstrings($_) ) if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 5403 5403
1929  
1930 REPARSE:
1931 6572 ▶ if ( ref eq 'ARRAY'
Branch: 14 branches
BranchTrueFalseTotal
if (ref $_ eq 'ARRAY' or UNIVERSAL::isa($_, 'IPC::Run::Win32Process') or not $cur_kid and ref $_ eq 'CODE') { } 1629 4943 6572
elsif (UNIVERSAL::isa($_, 'IPC::Run::IO')) { } 2 4941 4943
elsif (UNIVERSAL::isa($_, 'IPC::Run::Timer')) { } 14 4927 4941
elsif (/^(\d*)>&(\d+)$/) { } 59 4868 4927
elsif (/^(\d*)<&(\d+)$/) { } 28 4840 4868
elsif (/^(\d*)<&-$/) { } 34 4806 4840
elsif (/^(\d*) (<pipe)() () () $/x or /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x or /^(\d*) (<) () () (.*)$/x) { } 818 3988 4806
elsif (/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x or /^() (&) (>pty) ( \w*)> () $/x or /^(\d*)() (>pty) ( \w*)> () $/x or /^() (&) (>>?) () (.*)$/x or /^(\d*)() (>>?) () (.*)$/x) { } 1730 2258 3988
elsif ($_ eq '|') { } 18 2240 2258
elsif ($_ eq '&') { } 31 2209 2240
elsif ($_ eq 'init') { } 38 2171 2209
elsif (not ref $_) { } 1002 1169 2171
elsif ($_ eq 'init') { } 0 1169 1169
elsif ($succinct and $first_parse) { } 1169 0 1169
Condition88%8/9
ref $_ eq "ARRAY" or UNIVERSAL::isa($_, "IPC::Run::Win32Process") or not $cur_kid and ref $_ eq "CODE"
l!l&&r!l&&!r
14811484943
ref $_ eq "ARRAY" or UNIVERSAL::isa($_, "IPC::Run::Win32Process")
l!l&&r!l&&!r
148105091
not $cur_kid and ref $_ eq "CODE"
!ll&&!rl&&r
38931050148
MC/DC75%3/4
ref $_ eq "ARRAY" or UNIVERSAL::isa($_, "IPC::Run::Win32Process") or not $cur_kid and ref $_ eq "CODE"
ref $_ eq "ARRAY" UNIVERSAL::isa($_, "IPC::Run::Win32Process") not $cur_kid ref $_ eq "CODE"
Truth table80%4/5
A or B or not(C) and D
A= ref $_ eq "ARRAY"B= UNIVERSAL::isa($_, "IPC::Run::Win32Process")C= not $cur_kidD= ref $_ eq "CODE"
ABCDresult
1XXX1
01XX1
00111
000X0
00100
1932 || UNIVERSAL::isa( $_, 'IPC::Run::Win32Process' )
1933 || ( !$cur_kid && ref eq 'CODE' ) ) {
1934 1629 ▶ croak "Process control symbol ('|', '&') missing" if $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
if $cur_kid 0 1629 1629
1935 1629 ▶ croak "Can't spawn a subroutine on Win32"
Branch: 1 branch
BranchTrueFalseTotal
if &Win32_MODE() and ref $_ eq "CODE" 0 1629 1629
Condition33%1/3
&Win32_MODE() and ref $_ eq "CODE"
!ll&&!rl&&r
162900
MC/DC0%0/2
&Win32_MODE() and ref $_ eq "CODE"
&Win32_MODE() ref $_ eq "CODE"
Truth table33%1/3
A and B
A= &Win32_MODE()B= ref $_ eq "CODE"
ABresult
0X0
100
111
1936 if Win32_MODE && ref eq "CODE";
1937 $cur_kid = {
1938 TYPE => 'cmd',
1939 VAL => $_,
1940 1629 NUM => @{ $self->{KIDS} } + 1,
1941 OPS => [],
1942 PID => '',
1943 RESULT => undef,
1944 };
1945  
1946 1629 ▶ unshift @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
if $next_kid_close_stdin 24 1605 1629
1947 TYPE => 'close',
1948 KFD => 0,
1949 } if $next_kid_close_stdin;
1950 1629 $next_kid_close_stdin = 0;
1951  
1952 1629 push @{ $self->{KIDS} }, $cur_kid;
1953 1629 $succinct = 1;
1954 }
1955  
1956 elsif ( UNIVERSAL::isa( $_, 'IPC::Run::IO' ) ) {
1957 2 push @{ $self->{IOS} }, $_;
1958 2 $cur_kid = undef;
1959 2 $succinct = 1;
1960 }
1961  
1962 elsif ( UNIVERSAL::isa( $_, 'IPC::Run::Timer' ) ) {
1963 14 push @{ $self->{TIMERS} }, $_;
1964 14 $cur_kid = undef;
1965 14 $succinct = 1;
1966 }
1967  
1968 elsif (/^(\d*)>&(\d+)$/) {
1969 59 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 7 52 59
1970 52 ▶ push @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 52 0 52
1971 TYPE => 'dup',
1972 KFD1 => $2,
1973 KFD2 => length $1 ? $1 : 1,
1974 };
1975 52 ▶ _debug "redirect operators now required" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 52 52
1976 52 $succinct = !$first_parse;
1977 }
1978  
1979 elsif (/^(\d*)<&(\d+)$/) {
1980 28 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 7 21 28
1981 21 ▶ push @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 21 0 21
1982 TYPE => 'dup',
1983 KFD1 => $2,
1984 KFD2 => length $1 ? $1 : 0,
1985 };
1986 21 $succinct = !$first_parse;
1987 }
1988  
1989 elsif (/^(\d*)<&-$/) {
1990 34 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 14 20 34
1991 20 ▶ push @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 20 0 20
1992 TYPE => 'close',
1993 KFD => length $1 ? $1 : 0,
1994 };
1995 20 $succinct = !$first_parse;
1996 }
1997  
1998 ▶ elsif (/^(\d*) (<pipe)() () () $/x
Condition100%6/6
/^(\d*) (<pipe)() () () $/x or /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x or /^(\d*) (<) () () (.*)$/x
l!l&&r!l&&!r
377813988
/^(\d*) (<pipe)() () () $/x or /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x
l!l&&r!l&&!r
3074769
MC/DC100%3/3
/^(\d*) (<pipe)() () () $/x or /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x or /^(\d*) (<) () () (.*)$/x
/^(\d*) (<pipe)() () () $/x /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x /^(\d*) (<) () () (.*)$/x
Truth table100%4/4
A or B or C
A= /^(\d*) (<pipe)() () () $/xB= /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/xC= /^(\d*) (<) () () (.*)$/x
ABCresult
1XX1
01X1
0011
0000
1999 || /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x
2000 || /^(\d*) (<) () () (.*)$/x ) {
2001 818 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 14 804 818
2002  
2003 804 $succinct = !$first_parse;
2004  
2005 804 my $type = $2 . $4;
2006  
2007 804 ▶ my $kfd = length $1 ? $1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 526 278 804
2008  
2009 804 my $pty_id;
2010 804 ▶ if ( $type eq '<pty<' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "<pty<") 7 797 804
2011 7 ▶ $pty_id = length $3 ? $3 : '0';
Branch: 1 branch
BranchTrueFalseTotal
length $3 ? : 0 7 7
2012 ## do the require here to cause early error reporting
2013 7 require IO::Pty;
2014 ## Just flag the pyt's existence for now. It'll be
2015 ## converted to a real IO::Pty by _open_pipes.
2016 7 $self->{PTYS}->{$pty_id} = undef;
2017 }
2018  
2019 804 my $source = $5;
2020  
2021 804 my @filters;
2022 my $binmode;
2023  
2024 804 ▶ unless ( length $source ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $source) 752 52 804
2025 752 ▶ if ( !$succinct ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($succinct) 277 475 752
2026 277 ▶ while ( @args > 1
Branch: 1 branch
BranchTrueFalseTotal
if (@args > 1 and ref $args[1] && !UNIVERSAL::isa($args[1], "IPC::Run::Timer") || UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")) 55 277 332
Condition88%8/9
@args > 1 and ref $args[1] && !UNIVERSAL::isa($args[1], "IPC::Run::Timer") || UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
!ll&&!rl&&r
3127922
ref $args[1] and not UNIVERSAL::isa($args[1], "IPC::Run::Timer") or UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
l!l&&r!l&&!r
4411246
ref $args[1] and not UNIVERSAL::isa($args[1], "IPC::Run::Timer")
!ll&&!rl&&r
257044
MC/DC50%2/4
@args > 1 and ref $args[1] && !UNIVERSAL::isa($args[1], "IPC::Run::Timer") || UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
@args > 1 ref $args[1] not UNIVERSAL::isa($args[1], "IPC::Run::Timer") UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
Truth table50%3/6
A and B and not(C) or D
A= @args > 1B= ref $args[1]C= not UNIVERSAL::isa($args[1], "IPC::Run::Timer")D= UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
ABCDresult
0XXX0
10X00
11000
111X1
10X11
11011
2027 && ( ( ref $args[1] && !UNIVERSAL::isa $args[1], "IPC::Run::Timer" ) || UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) ) {
2028 55 ▶ if ( UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($args[0], 'IPC::Run::binmode_pseudo_filter')) { } 42 13 55
2029 42 $binmode = shift(@args)->();
2030 }
2031 else {
2032 13 push @filters, shift @args;
2033 }
2034 }
2035 }
2036 752 $source = shift @args;
2037 752 ▶ croak "'$_' missing a source" if _empty $source;
Branch: 1 branch
BranchTrueFalseTotal
if &_empty($source) 0 752 752
2038  
2039 _debug(
2040 752 ▶ 'Kid ', $cur_kid->{NUM}, "'s input fd ", $kfd,
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() and @filters 0 752 752
Condition33%1/3
&_debugging_details() and @filters
!ll&&!rl&&r
75200
MC/DC0%0/2
&_debugging_details() and @filters
&_debugging_details() @filters
Truth table33%1/3
A and B
A= &_debugging_details()B= @filters
ABresult
0X0
100
111
2041 ' has ', scalar(@filters), ' filters.'
2042 ) if _debugging_details && @filters;
2043 }
2044  
2045 804 my IPC::Run::IO $pipe = IPC::Run::IO->_new_internal( $type, $kfd, $pty_id, $source, $binmode, @filters );
2046  
2047 804 ▶ if ( ( ref $source eq 'GLOB' || UNIVERSAL::isa $source, 'IO::Handle' )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $source eq "GLOB" || UNIVERSAL::isa($source, "IO::Handle") and not $type =~ /^<p(ty<|ipe)$/) 56 748 804
Condition100%6/6
ref $source eq "GLOB" || UNIVERSAL::isa($source, "IO::Handle") and not $type =~ /^<p(ty<|ipe)$/
!ll&&!rl&&r
7202856
ref $source eq "GLOB" or UNIVERSAL::isa($source, "IO::Handle")
l!l&&r!l&&!r
5727720
MC/DC100%3/3
ref $source eq "GLOB" || UNIVERSAL::isa($source, "IO::Handle") and not $type =~ /^<p(ty<|ipe)$/
ref $source eq "GLOB" UNIVERSAL::isa($source, "IO::Handle") not $type =~ /^<p(ty<|ipe)$/
Truth table80%4/5
A or B and not(C)
A= ref $source eq "GLOB"B= UNIVERSAL::isa($source, "IO::Handle")C= not $type =~ /^<p(ty<|ipe)$/
ABCresult
00X0
1X00
0100
1X11
0111
2048 && $type !~ /^<p(ty<|ipe)$/ ) {
2049 56 ▶ _debug "setting DONT_CLOSE" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 56 56
2050 56 $pipe->{DONT_CLOSE} = 1; ## this FD is not closed by us.
2051 56 ▶ _dont_inherit($source) if Win32_MODE;
Branch: 1 branch
BranchTrueFalseTotal
if &Win32_MODE() 0 56 56
2052 }
2053  
2054 804 push @{ $cur_kid->{OPS} }, $pipe;
2055 }
2056  
2057 ▶ elsif (
Condition85%18/21
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x or /^() (&) (>pty) ( \w*)> () $/x or /^(\d*)() (>pty) ( \w*)> () $/x or /^() (&) (>>?) () (.*)$/x or /^(\d*)() (>>?) () (.*)$/x
l!l&&r!l&&!r
8916412258
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x or /^() (&) (>pty) ( \w*)> () $/x or /^(\d*)() (>pty) ( \w*)> () $/x or /^() (&) (>>?) () (.*)$/x
l!l&&r!l&&!r
8723899
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x or /^() (&) (>pty) ( \w*)> () $/x or /^(\d*)() (>pty) ( \w*)> () $/x
l!l&&r!l&&!r
7893901
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x or /^() (&) (>pty) ( \w*)> () $/x
l!l&&r!l&&!r
7803910
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x
l!l&&r!l&&!r
25533910
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x
l!l&&r!l&&!r
2503963
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x
l!l&&r!l&&!r
2503963
MC/DC62%5/8
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x or /^() (&) (>pty) ( \w*)> () $/x or /^(\d*)() (>pty) ( \w*)> () $/x or /^() (&) (>>?) () (.*)$/x or /^(\d*)() (>>?) () (.*)$/x
/^() (>>?) (&) () (.*)$/x /^() (&) (>pipe) () () $/x /^() (>pipe)(&) () () $/x /^(\d*)() (>pipe) () () $/x /^() (&) (>pty) ( \w*)> () $/x /^(\d*)() (>pty) ( \w*)> () $/x /^() (&) (>>?) () (.*)$/x /^(\d*)() (>>?) () (.*)$/x
Truth table66%6/9
A or B or C or D or E or F or G or H
A= /^() (>>?) (&) () (.*)$/xB= /^() (&) (>pipe) () () $/xC= /^() (>pipe)(&) () () $/xD= /^(\d*)() (>pipe) () () $/xE= /^() (&) (>pty) ( \w*)> () $/xF= /^(\d*)() (>pty) ( \w*)> () $/xG= /^() (&) (>>?) () (.*)$/xH= /^(\d*)() (>>?) () (.*)$/x
ABCDEFGHresult
1XXXXXXX1
01XXXXXX1
001XXXXX1
0001XXXX1
00001XXX1
000001XX1
0000001X1
000000011
000000000
2058 /^() (>>?) (&) () (.*)$/x
2059 || /^() (&) (>pipe) () () $/x
2060 || /^() (>pipe)(&) () () $/x
2061 || /^(\d*)() (>pipe) () () $/x
2062 || /^() (&) (>pty) ( \w*)> () $/x
2063 ## TODO: || /^() (>pty) (\d*)> (&) () $/x
2064 || /^(\d*)() (>pty) ( \w*)> () $/x
2065 || /^() (&) (>>?) () (.*)$/x || /^(\d*)() (>>?) () (.*)$/x
2066 ) {
2067 1730 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 21 1709 1730
2068  
2069 1709 $succinct = !$first_parse;
2070  
2071 1709 ▶ my $type = (
Branch: 2 branches
BranchTrueFalseTotal
$2 eq '>pipe' || $3 eq '>pipe' ? : 53 1656 1709
$2 eq '>pty' || $3 eq '>pty' ? : 9 1647 1656
Condition66%4/6
$2 eq ">pipe" or $3 eq ">pipe"
l!l&&r!l&&!r
0531656
$2 eq ">pty" or $3 eq ">pty"
l!l&&r!l&&!r
091647
MC/DC50%1/2
$2 eq ">pipe" or $3 eq ">pipe"
$2 eq ">pipe" $3 eq ">pipe"
MC/DC50%1/2
$2 eq ">pty" or $3 eq ">pty"
$2 eq ">pty" $3 eq ">pty"
Truth table66%2/3
A or B
A= $2 eq ">pipe"B= $3 eq ">pipe"
ABresult
1X1
011
000
Truth table66%2/3
A or B
A= $2 eq ">pty"B= $3 eq ">pty"
ABresult
1X1
011
000
2072 $2 eq '>pipe' || $3 eq '>pipe' ? '>pipe'
2073 : $2 eq '>pty' || $3 eq '>pty' ? '>pty>'
2074 : '>'
2075 );
2076 1709 ▶ my $kfd = length $1 ? $1 : 1;
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 1011 698 1709
2077 1709 ▶ my $trunc = !( $2 eq '>>' || $3 eq '>>' );
Condition66%2/3
$2 eq '>>' || $3 eq '>>'
l!l&&r!l&&!r
0381671
MC/DC50%1/2
$2 eq '>>' || $3 eq '>>'
$2 eq '>>' $3 eq '>>'
Truth table66%2/3
A || B
A= $2 eq '>>'B= $3 eq '>>'
ABresult
1X1
011
000
2078 1709 ▶ my $pty_id = (
Branch: 2 branches
BranchTrueFalseTotal
$2 eq '>pty' || $3 eq '>pty' ? : 9 1700 1709
length $4 ? : 0 9 9
Condition66%2/3
$2 eq ">pty" or $3 eq ">pty"
l!l&&r!l&&!r
091700
MC/DC50%1/2
$2 eq ">pty" or $3 eq ">pty"
$2 eq ">pty" $3 eq ">pty"
Truth table66%2/3
A or B
A= $2 eq ">pty"B= $3 eq ">pty"
ABresult
1X1
011
000
2079 $2 eq '>pty' || $3 eq '>pty'
2080 ? length $4
2081 ? $4
2082 : 0
2083 : undef
2084 );
2085  
2086 1709 ▶ my $stderr_too =
Condition100%9/9
$2 eq '&' || $3 eq '&' || !length($1) && substr($type, 0, 4) eq '>pty'
l!l&&r!l&&!r
2091680
$2 eq "&" or $3 eq "&"
l!l&&r!l&&!r
2181689
not length $1 and substr($type, 0, 4) eq ">pty"
!ll&&!rl&&r
10116699
MC/DC100%4/4
$2 eq '&' || $3 eq '&' || !length($1) && substr($type, 0, 4) eq '>pty'
$2 eq "&" $3 eq "&" not length $1 substr($type, 0, 4) eq ">pty"
Truth table100%5/5
A or B || not(C) and D
A= $2 eq "&"B= $3 eq "&"C= not length $1D= substr($type, 0, 4) eq ">pty"
ABCDresult
1XXX1
01XX1
00111
000X0
00100
2087 $2 eq '&'
2088 || $3 eq '&'
2089 || ( !length $1 && substr( $type, 0, 4 ) eq '>pty' );
2090  
2091 1709 my $dest = $5;
2092 1709 my @filters;
2093 1709 my $binmode = 0;
2094 1709 ▶ unless ( length $dest ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $dest) 1542 167 1709
2095 1542 ▶ if ( !$succinct ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($succinct) 848 694 1542
2096 ## unshift...shift: '>' filters source...sink left...right
2097 848 ▶ while ( @args > 1
Branch: 1 branch
BranchTrueFalseTotal
if (@args > 1 and ref $args[1] && !UNIVERSAL::isa($args[1], "IPC::Run::Timer") || UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")) 66 848 914
Condition88%8/9
@args > 1 and ref $args[1] && !UNIVERSAL::isa($args[1], "IPC::Run::Timer") || UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
!ll&&!rl&&r
53935322
ref $args[1] and not UNIVERSAL::isa($args[1], "IPC::Run::Timer") or UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
l!l&&r!l&&!r
5511309
ref $args[1] and not UNIVERSAL::isa($args[1], "IPC::Run::Timer")
!ll&&!rl&&r
320055
MC/DC50%2/4
@args > 1 and ref $args[1] && !UNIVERSAL::isa($args[1], "IPC::Run::Timer") || UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
@args > 1 ref $args[1] not UNIVERSAL::isa($args[1], "IPC::Run::Timer") UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
Truth table50%3/6
A and B and not(C) or D
A= @args > 1B= ref $args[1]C= not UNIVERSAL::isa($args[1], "IPC::Run::Timer")D= UNIVERSAL::isa($args[0], "IPC::Run::binmode_pseudo_filter")
ABCDresult
0XXX0
10X00
11000
111X1
10X11
11011
2098 && ( ( ref $args[1] && !UNIVERSAL::isa $args[1], "IPC::Run::Timer" ) || UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) ) {
2099 66 ▶ if ( UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($args[0], 'IPC::Run::binmode_pseudo_filter')) { } 49 17 66
2100 49 $binmode = shift(@args)->();
2101 }
2102 else {
2103 17 unshift @filters, shift @args;
2104 }
2105 }
2106 }
2107  
2108 1542 ▶ if ( @args && ref $args[0] eq 'IPC::Run::Undef' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args and ref $args[0] eq 'IPC::Run::Undef') { } 2 1540 1542
Condition66%2/3
@args and ref $args[0] eq "IPC::Run::Undef"
!ll&&!rl&&r
015402
MC/DC50%1/2
@args and ref $args[0] eq "IPC::Run::Undef"
@args ref $args[0] eq "IPC::Run::Undef"
Truth table66%2/3
A and B
A= @argsB= ref $args[0] eq "IPC::Run::Undef"
ABresult
0X0
100
111
2109 2 require Symbol;
2110 2 ${ $args[0] } = $dest = Symbol::gensym();
2111 2 shift @args;
2112 }
2113 else {
2114 1540 $dest = shift @args;
2115 }
2116  
2117 _debug(
2118 1542 ▶ 'Kid ', $cur_kid->{NUM}, "'s output fd ", $kfd,
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() and @filters 0 1542 1542
Condition33%1/3
&_debugging_details() and @filters
!ll&&!rl&&r
154200
MC/DC0%0/2
&_debugging_details() and @filters
&_debugging_details() @filters
Truth table33%1/3
A and B
A= &_debugging_details()B= @filters
ABresult
0X0
100
111
2119 ' has ', scalar(@filters), ' filters.'
2120 ) if _debugging_details && @filters;
2121  
2122 1542 ▶ if ( $type eq '>pty>' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq ">pty>") 9 1533 1542
2123 ## do the require here to cause early error reporting
2124 9 require IO::Pty;
2125 ## Just flag the pyt's existence for now. _open_pipes()
2126 ## will new an IO::Pty for each key.
2127 9 $self->{PTYS}->{$pty_id} = undef;
2128 }
2129 }
2130  
2131 1709 ▶ croak "'$_' missing a destination" if _empty $dest;
Branch: 1 branch
BranchTrueFalseTotal
if &_empty($dest) 0 1709 1709
2132 1709 my $pipe = IPC::Run::IO->_new_internal( $type, $kfd, $pty_id, $dest, $binmode, @filters );
2133 1709 $pipe->{TRUNC} = $trunc;
2134  
2135 1709 ▶ if ( ( UNIVERSAL::isa( $dest, 'GLOB' ) || UNIVERSAL::isa( $dest, 'IO::Handle' ) )
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($dest, "GLOB") || UNIVERSAL::isa($dest, "IO::Handle") and not $type =~ /^>(pty>|pipe)$/) 54 1655 1709
Condition83%5/6
UNIVERSAL::isa($dest, "GLOB") || UNIVERSAL::isa($dest, "IO::Handle") and not $type =~ /^>(pty>|pipe)$/
!ll&&!rl&&r
16035254
UNIVERSAL::isa($dest, "GLOB") or UNIVERSAL::isa($dest, "IO::Handle")
l!l&&r!l&&!r
10601603
MC/DC66%2/3
UNIVERSAL::isa($dest, "GLOB") || UNIVERSAL::isa($dest, "IO::Handle") and not $type =~ /^>(pty>|pipe)$/
UNIVERSAL::isa($dest, "GLOB") UNIVERSAL::isa($dest, "IO::Handle") not $type =~ /^>(pty>|pipe)$/
Truth table60%3/5
A or B and not(C)
A= UNIVERSAL::isa($dest, "GLOB")B= UNIVERSAL::isa($dest, "IO::Handle")C= not $type =~ /^>(pty>|pipe)$/
ABCresult
00X0
1X00
0100
1X11
0111
2136 && $type !~ /^>(pty>|pipe)$/ ) {
2137 54 ▶ _debug "setting DONT_CLOSE" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 54 54
2138 54 $pipe->{DONT_CLOSE} = 1; ## this FD is not closed by us.
2139 }
2140 1709 push @{ $cur_kid->{OPS} }, $pipe;
2141 1709 ▶ push @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
if $stderr_too 29 1680 1709
2142 TYPE => 'dup',
2143 KFD1 => 1,
2144 KFD2 => 2,
2145 } if $stderr_too;
2146 }
2147  
2148 elsif ( $_ eq "|" ) {
2149 18 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 7 11 18
2150 11 unshift @{ $cur_kid->{OPS} }, {
2151 TYPE => '|',
2152 KFD => 1,
2153 };
2154 11 $succinct = 1;
2155 11 $assumed_fd = 1;
2156 11 $cur_kid = undef;
2157 }
2158  
2159 elsif ( $_ eq "&" ) {
2160 31 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 7 24 31
2161 24 $next_kid_close_stdin = 1;
2162 24 $succinct = 1;
2163 24 $assumed_fd = 0;
2164 24 $cur_kid = undef;
2165 }
2166  
2167 elsif ( $_ eq 'init' ) {
2168 38 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 0 38 38
2169 38 push @{ $cur_kid->{OPS} }, {
2170 TYPE => 'init',
2171 SUB => shift @args,
2172 };
2173 }
2174  
2175 elsif ( !ref $_ ) {
2176 1002 $self->{$_} = shift @args;
2177 }
2178  
2179 elsif ( $_ eq 'init' ) {
2180 0 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 0 0 0
2181 0 push @{ $cur_kid->{OPS} }, {
2182 TYPE => 'init',
2183 SUB => shift @args,
2184 };
2185 }
2186  
2187 ▶ elsif ( $succinct && $first_parse ) {
Condition33%1/3
$succinct and $first_parse
!ll&&!rl&&r
001169
MC/DC0%0/2
$succinct and $first_parse
$succinct $first_parse
Truth table33%1/3
A and B
A= $succinctB= $first_parse
ABresult
0X0
100
111
2188 ## It's not an opcode, and no explicit opcodes have been
2189 ## seen yet, so assume it's a file name.
2190 1169 unshift @args, $_;
2191 1169 ▶ if ( !$assumed_fd ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $assumed_fd) { } 475 694 1169
2192 475 $_ = "$assumed_fd<",
2193 }
2194 else {
2195 694 $_ = "$assumed_fd>",
2196 }
2197 1169 ▶ _debug "assuming '", $_, "'" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1169 1169
2198 1169 ++$assumed_fd;
2199 1169 $first_parse = 0;
2200 1169 goto REPARSE;
2201 }
2202  
2203 else {
2204 0 ▶ croak join(
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 0 0
2205 '',
2206 'Unexpected ',
2207 ( ref() ? $_ : 'scalar' ),
2208 ' in harness() parameter ',
2209 $arg_count - @args
2210 );
2211 }
2212 };
2213 5403 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 77 5326 5403
2214 77 push @errs, $@;
2215 77 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 77 77
2216 }
2217 }
2218 }
2219  
2220 1700 ▶ die join( '', @errs ) if @errs;
Branch: 1 branch
BranchTrueFalseTotal
if @errs 77 1623 1700
2221  
2222 1623 $self->{STATE} = _harnessed;
2223  
2224 # $self->timeout( $options->{timeout} ) if exists $options->{timeout};
2225 1623 return $self;
2226 }
2227  
2228 sub _open_pipes {
2229 1481 ▶ my IPC::Run $self = shift;
Subroutine _open_pipes: called CC=81 SCAR=49.1
2230  
2231 1481 my @errs;
2232  
2233 my @close_on_fail;
2234  
2235 ## When a pipe character is seen, a pipe is created. $pipe_read_fd holds
2236 ## the dangling read end of the pipe until we get to the next process.
2237 1481 my $pipe_read_fd;
2238  
2239 ## Output descriptors for the last command are shared by all children.
2240 ## @output_fds_accum accumulates the current set of output fds.
2241 1481 my @output_fds_accum;
2242  
2243 1481 for ( sort keys %{ $self->{PTYS} } ) {
2244 14 ▶ _debug "opening pty '", $_, "'" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 14 14
2245 14 my $pty = _pty;
2246 14 $self->{PTYS}->{$_} = $pty;
2247 }
2248  
2249 1481 for ( @{ $self->{IOS} } ) {
2250 2 eval { $_->init; };
2251 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 2 2
2252 0 push @errs, $@;
2253 0 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
2254 }
2255 else {
2256 2 push @close_on_fail, $_;
2257 }
2258 }
2259  
2260 ## Loop through the kids and their OPS, interpreting any that require
2261 ## parent-side actions.
2262 1481 for my $kid ( @{ $self->{KIDS} } ) {
2263 1514 ▶ if ( ref $kid->{VAL} eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $kid->{"VAL"} eq "ARRAY") 1366 148 1514
2264 1366 $kid->{PATH} = _search_path $kid->{VAL}->[0];
2265 }
2266 1512 ▶ if ( defined $pipe_read_fd ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pipe_read_fd) 11 1501 1512
2267 11 ▶ _debug "placing write end of pipe on kid $kid->{NUM}'s stdin"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 11 11
2268 if _debugging_details;
2269 11 unshift @{ $kid->{OPS} }, {
2270 TYPE => 'PIPE', ## Prevent next loop from triggering on this
2271 KFD => 0,
2272 TFD => $pipe_read_fd,
2273 };
2274 11 $pipe_read_fd = undef;
2275 }
2276 1512 @output_fds_accum = ();
2277 1512 for my $op ( @{ $kid->{OPS} } ) {
2278  
2279 # next if $op->{IS_DEBUG};
2280 2676 my $ok = eval {
2281 2676 ▶ if ( $op->{TYPE} eq '<' ) {
Branch: 8 branches
BranchTrueFalseTotal
if ($op->{'TYPE'} eq '<') { } 749 1927 2676
elsif ($op->{'TYPE'} eq '<pipe') { } 28 1899 1927
elsif ($op->{'TYPE'} eq '<pty<') { } 7 1892 1899
elsif ($op->{'TYPE'} eq '>') { } 1630 262 1892
elsif ($op->{'TYPE'} eq '>pipe') { } 52 210 262
elsif ($op->{'TYPE'} eq '>pty>') { } 9 201 210
elsif ($op->{'TYPE'} eq '|') { } 11 190 201
elsif ($op->{'TYPE'} eq '&') { } 0 190 190
2282 749 my $source = $op->{SOURCE};
2283 749 ▶ if ( !ref $source ) {
Branch: 4 branches
BranchTrueFalseTotal
if (not ref $source) { } 71 678 749
elsif (UNIVERSAL::isa($source, 'GLOB') or UNIVERSAL::isa($source, 'IO::Handle')) { } 56 622 678
elsif (UNIVERSAL::isa($source, 'SCALAR')) { } 547 75 622
elsif (UNIVERSAL::isa($source, 'CODE')) { } 68 7 75
2284 _debug(
2285 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2286 71 ▶ " from '" . $source, "' (read only)"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 71 71
2287 ) if _debugging_details;
2288 croak "simulated open failure"
2289 71 ▶ if $self->{_simulate_open_failure};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_simulate_open_failure"} 7 64 71
2290 64 $op->{TFD} = _sysopen( $source, O_RDONLY );
2291 45 push @close_on_fail, $op->{TFD};
2292 }
2293 ▶ elsif (UNIVERSAL::isa( $source, 'GLOB' )
Condition100%3/3
UNIVERSAL::isa($source, "GLOB") or UNIVERSAL::isa($source, "IO::Handle")
l!l&&r!l&&!r
2927622
MC/DC100%2/2
UNIVERSAL::isa($source, "GLOB") or UNIVERSAL::isa($source, "IO::Handle")
UNIVERSAL::isa($source, "GLOB") UNIVERSAL::isa($source, "IO::Handle")
Truth table100%3/3
A or B
A= UNIVERSAL::isa($source, "GLOB")B= UNIVERSAL::isa($source, "IO::Handle")
ABresult
1X1
011
000
2294 || UNIVERSAL::isa( $source, 'IO::Handle' ) ) {
2295 56 ▶ croak "Unopened filehandle in input redirect for $op->{KFD}"
Branch: 1 branch
BranchTrueFalseTotal
unless defined fileno $source 0 56 56
2296 unless defined fileno $source;
2297 56 $op->{TFD} = fileno $source;
2298 _debug(
2299 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2300 " from fd ", $op->{TFD}
2301 56 ▶ ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 56 56
2302 }
2303 elsif ( UNIVERSAL::isa( $source, 'SCALAR' ) ) {
2304 _debug(
2305 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2306 547 ▶ " from SCALAR"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 547 547
2307 ) if _debugging_details;
2308  
2309 547 $op->open_pipe( $self->_debug_fd );
2310 547 push @close_on_fail, $op->{KFD}, $op->{FD};
2311  
2312 547 my $s = '';
2313 547 $op->{KIN_REF} = \$s;
2314 }
2315 elsif ( UNIVERSAL::isa( $source, 'CODE' ) ) {
2316 68 ▶ _debug( 'kid ', $kid->{NUM}, ' to read ', $op->{KFD}, ' from CODE' ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 68 68
2317  
2318 68 $op->open_pipe( $self->_debug_fd );
2319 68 push @close_on_fail, $op->{KFD}, $op->{FD};
2320  
2321 68 my $s = '';
2322 68 $op->{KIN_REF} = \$s;
2323 }
2324 else {
2325 7 croak( "'" . ref($source) . "' not allowed as a source for input redirection" );
2326 }
2327 716 $op->_init_filters;
2328 }
2329 elsif ( $op->{TYPE} eq '<pipe' ) {
2330 _debug(
2331 'kid to read ', $op->{KFD},
2332 28 ▶ ' from a pipe IPC::Run opens and returns',
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 28 28
2333 ) if _debugging_details;
2334  
2335 28 my ( $r, $w ) = $op->open_pipe( $self->_debug_fd, $op->{SOURCE} );
2336 _debug "caller will write to ", fileno $op->{SOURCE}
2337 28 ▶ if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 28 28
2338  
2339 28 $op->{TFD} = $r;
2340 28 $op->{FD} = undef; # we don't manage this fd
2341 28 $op->_init_filters;
2342 }
2343 elsif ( $op->{TYPE} eq '<pty<' ) {
2344 _debug(
2345 7 ▶ 'kid to read ', $op->{KFD}, " from pty '", $op->{PTY_ID}, "'",
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 7 7
2346 ) if _debugging_details;
2347  
2348 7 for my $source ( $op->{SOURCE} ) {
2349 7 ▶ if ( UNIVERSAL::isa( $source, 'SCALAR' ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (UNIVERSAL::isa($source, 'SCALAR')) { } 7 0 7
elsif (UNIVERSAL::isa($source, 'CODE')) { } 0 0 0
2350 _debug(
2351 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2352 7 ▶ " from SCALAR via pty '", $op->{PTY_ID}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 7 7
2353 ) if _debugging_details;
2354  
2355 7 my $s = '';
2356 7 $op->{KIN_REF} = \$s;
2357 }
2358 elsif ( UNIVERSAL::isa( $source, 'CODE' ) ) {
2359 _debug(
2360 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2361 0 ▶ " from CODE via pty '", $op->{PTY_ID}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
2362 ) if _debugging_details;
2363 0 my $s = '';
2364 0 $op->{KIN_REF} = \$s;
2365 }
2366 else {
2367 0 croak( "'" . ref($source) . "' not allowed as a source for '<pty<' redirection" );
2368 }
2369 }
2370 7 $op->{FD} = $self->{PTYS}->{ $op->{PTY_ID} }->fileno;
2371 7 $op->{TFD} = undef; # The fd isn't known until after fork().
2372 7 $op->_init_filters;
2373 }
2374 elsif ( $op->{TYPE} eq '>' ) {
2375 ## N> output redirection.
2376 1630 my $dest = $op->{DEST};
2377 1630 ▶ if ( !ref $dest ) {
Branch: 4 branches
BranchTrueFalseTotal
if (not ref $dest) { } 171 1459 1630
elsif (UNIVERSAL::isa($dest, 'GLOB')) { } 54 1405 1459
elsif (UNIVERSAL::isa($dest, 'SCALAR')) { } 1300 105 1405
elsif (UNIVERSAL::isa($dest, 'CODE')) { } 98 7 105
2378 _debug(
2379 "kid ", $kid->{NUM}, " to write ", $op->{KFD},
2380 " to '", $dest, "' (write only, create, ",
2381 171 ▶ ( $op->{TRUNC} ? 'truncate' : 'append' ),
Branch: 2 branches
BranchTrueFalseTotal
if &_debugging_details() 0 171 171
$op->{'TRUNC'} ? : 0 0 0
2382 ")"
2383 ) if _debugging_details;
2384 croak "simulated open failure"
2385 171 ▶ if $self->{_simulate_open_failure};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_simulate_open_failure"} 7 164 171
2386 $op->{TFD} = _sysopen(
2387 $dest,
2388 164 ▶ ( O_WRONLY | O_CREAT | ( $op->{TRUNC} ? O_TRUNC : O_APPEND ) )
Branch: 1 branch
BranchTrueFalseTotal
$op->{'TRUNC'} ? : 130 34 164
2389 );
2390 164 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) 0 164 164
2391 ## I have no idea why this is needed to make the current
2392 ## file position survive the gyrations TFD must go
2393 ## through...
2394 0 POSIX::lseek( $op->{TFD}, 0, POSIX::SEEK_END() );
2395 }
2396 164 push @close_on_fail, $op->{TFD};
2397 }
2398 elsif ( UNIVERSAL::isa( $dest, 'GLOB' ) ) {
2399 54 ▶ croak("Unopened filehandle in output redirect, command $kid->{NUM}") unless defined fileno $dest;
Branch: 1 branch
BranchTrueFalseTotal
unless defined fileno $dest 0 54 54
2400 ## Turn on autoflush, mostly just to flush out
2401 ## existing output.
2402 54 my $old_fh = select($dest);
2403 54 $| = 1;
2404 54 select($old_fh);
2405 54 $op->{TFD} = fileno $dest;
2406 54 ▶ _debug( 'kid to write ', $op->{KFD}, ' to handle ', $op->{TFD} ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 54 54
2407 }
2408 elsif ( UNIVERSAL::isa( $dest, 'SCALAR' ) ) {
2409 1300 ▶ _debug( "kid ", $kid->{NUM}, " to write $op->{KFD} to SCALAR" ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1300 1300
2410  
2411 1300 $op->open_pipe( $self->_debug_fd );
2412 1300 push @close_on_fail, $op->{FD}, $op->{TFD};
2413 1300 ▶ $$dest = '' if $op->{TRUNC};
Branch: 1 branch
BranchTrueFalseTotal
if $op->{"TRUNC"} 1300 0 1300
2414 }
2415 elsif ( UNIVERSAL::isa( $dest, 'CODE' ) ) {
2416 98 ▶ _debug("kid $kid->{NUM} to write $op->{KFD} to CODE") if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 98 98
2417  
2418 98 $op->open_pipe( $self->_debug_fd );
2419 98 push @close_on_fail, $op->{FD}, $op->{TFD};
2420 }
2421 else {
2422 7 croak( "'" . ref($dest) . "' not allowed as a sink for output redirection" );
2423 }
2424 1616 $output_fds_accum[ $op->{KFD} ] = $op;
2425 1616 $op->_init_filters;
2426 }
2427  
2428 elsif ( $op->{TYPE} eq '>pipe' ) {
2429 ## N> output redirection to a pipe we open, but don't select()
2430 ## on.
2431 _debug(
2432 "kid ", $kid->{NUM}, " to write ", $op->{KFD},
2433 52 ▶ ' to a pipe IPC::Run opens and returns'
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 52 52
2434 ) if _debugging_details;
2435  
2436 52 my ( $r, $w ) = $op->open_pipe( $self->_debug_fd, $op->{DEST} );
2437 _debug "caller will read from ", fileno $op->{DEST}
2438 52 ▶ if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 52 52
2439  
2440 52 $op->{TFD} = $w;
2441 52 $op->{FD} = undef; # we don't manage this fd
2442 52 $op->_init_filters;
2443  
2444 52 $output_fds_accum[ $op->{KFD} ] = $op;
2445 }
2446 elsif ( $op->{TYPE} eq '>pty>' ) {
2447 9 my $dest = $op->{DEST};
2448 9 ▶ if ( UNIVERSAL::isa( $dest, 'SCALAR' ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (UNIVERSAL::isa($dest, 'SCALAR')) { } 9 0 9
elsif (UNIVERSAL::isa($dest, 'CODE')) { } 0 0 0
2449 _debug(
2450 "kid ", $kid->{NUM}, " to write ", $op->{KFD},
2451 9 ▶ " to SCALAR via pty '", $op->{PTY_ID}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 9 9
2452 ) if _debugging_details;
2453  
2454 9 ▶ $$dest = '' if $op->{TRUNC};
Branch: 1 branch
BranchTrueFalseTotal
if $op->{"TRUNC"} 9 0 9
2455 }
2456 elsif ( UNIVERSAL::isa( $dest, 'CODE' ) ) {
2457 _debug(
2458 "kid ", $kid->{NUM}, " to write ", $op->{KFD},
2459 0 ▶ " to CODE via pty '", $op->{PTY_ID}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
2460 ) if _debugging_details;
2461 }
2462 else {
2463 0 croak( "'" . ref($dest) . "' not allowed as a sink for output redirection" );
2464 }
2465  
2466 9 $op->{FD} = $self->{PTYS}->{ $op->{PTY_ID} }->fileno;
2467 9 $op->{TFD} = undef; # The fd isn't known until after fork().
2468 9 $output_fds_accum[ $op->{KFD} ] = $op;
2469 9 $op->_init_filters;
2470 }
2471 elsif ( $op->{TYPE} eq '|' ) {
2472 11 ▶ _debug( "pipelining $kid->{NUM} and " . ( $kid->{NUM} + 1 ) ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 11 11
2473 11 ( $pipe_read_fd, $op->{TFD} ) = _pipe;
2474 11 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) 0 11 11
2475 0 _dont_inherit($pipe_read_fd);
2476 0 _dont_inherit( $op->{TFD} );
2477 }
2478 11 @output_fds_accum = ();
2479 }
2480 elsif ( $op->{TYPE} eq '&' ) {
2481 0 @output_fds_accum = ();
2482 } # end if $op->{TYPE} tree
2483 2629 1;
2484 }; # end eval
2485 2676 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 47 2629 2676
2486 47 push @errs, $@;
2487 47 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 47 47
2488 }
2489 } # end for ( OPS }
2490 }
2491  
2492 1479 ▶ if (@errs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@errs) 47 1432 1479
2493 47 for (@close_on_fail) {
2494 19 _close($_);
2495 19 $_ = undef;
2496 }
2497 47 for ( keys %{ $self->{PTYS} } ) {
2498 0 ▶ next unless $self->{PTYS}->{$_};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"PTYS"}{$_} 0 0 0
2499 0 close $self->{PTYS}->{$_};
2500 0 $self->{PTYS}->{$_} = undef;
2501 }
2502 47 die join( '', @errs );
2503 }
2504  
2505 ## give all but the last child all of the output file descriptors
2506 ## These will be reopened (and thus rendered useless) if the child
2507 ## dup2s on to these descriptors, since we unshift these. This way
2508 ## each process emits output to the same file descriptors that the
2509 ## last child will write to. This is probably not quite correct,
2510 ## since each child should write to the file descriptors inherited
2511 ## from the parent.
2512 ## TODO: fix the inheritance of output file descriptors.
2513 ## NOTE: This sharing of OPS among kids means that we can't easily put
2514 ## a kid number in each OPS structure to ping the kid when all ops
2515 ## have closed (when $self->{PIPES} has emptied). This means that we
2516 ## need to scan the KIDS whenever @{$self->{PIPES}} is empty to see
2517 ## if there any of them are still alive.
2518 1432 ▶ for ( my $num = 0; $num < $#{ $self->{KIDS} }; ++$num ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num < $#{$$self{"KIDS"};}) 35 1432 1467
2519 35 for ( reverse @output_fds_accum ) {
2520 60 ▶ next unless defined $_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 20 40 60
2521 _debug(
2522 'kid ', $self->{KIDS}->[$num]->{NUM}, ' also to write ', $_->{KFD},
2523 ' to ', ref $_->{DEST}
2524 40 ▶ ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 40 40
2525 40 unshift @{ $self->{KIDS}->[$num]->{OPS} }, $_;
2526 }
2527 }
2528  
2529 ## Open the debug pipe if we need it
2530 ## Create the list of PIPES we need to scan and the bit vectors needed by
2531 ## select(). Do this first so that _cleanup can _clobber() them if an
2532 ## exception occurs.
2533 1432 @{ $self->{PIPES} } = ();
2534 1432 $self->{RIN} = '';
2535 1432 $self->{WIN} = '';
2536 1432 $self->{EIN} = '';
2537 ## PIN is a vec()tor that indicates who's paused.
2538 1432 $self->{PIN} = '';
2539 1432 for my $kid ( @{ $self->{KIDS} } ) {
2540 1465 for ( @{ $kid->{OPS} } ) {
2541 2650 ▶ if ( defined $_->{FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_->{"FD"}) 2069 581 2650
2542 _debug(
2543 'kid ', $kid->{NUM}, '[', $kid->{PID}, "]'s ", $_->{KFD},
2544 ' is my ', $_->{FD}
2545 2069 ▶ ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2069 2069
2546 2069 ▶ vec( $self->{ $_->{TYPE} =~ /^</ ? 'WIN' : 'RIN' }, $_->{FD}, 1 ) = 1;
Branch: 1 branch
BranchTrueFalseTotal
$_->{'TYPE'} =~ /^</ ? : 622 1447 2069
2547  
2548 # vec( $self->{EIN}, $_->{FD}, 1 ) = 1;
2549 2069 push @{ $self->{PIPES} }, $_;
2550 }
2551 }
2552 }
2553  
2554 1432 for my $io ( @{ $self->{IOS} } ) {
2555 2 my $fd = $io->fileno;
2556 2 ▶ vec( $self->{RIN}, $fd, 1 ) = 1 if $io->mode =~ /r/;
Branch: 1 branch
BranchTrueFalseTotal
if $io->mode =~ /r/ 1 1 2
2557 2 ▶ vec( $self->{WIN}, $fd, 1 ) = 1 if $io->mode =~ /w/;
Branch: 1 branch
BranchTrueFalseTotal
if $io->mode =~ /w/ 1 1 2
2558  
2559 # vec( $self->{EIN}, $fd, 1 ) = 1;
2560 2 push @{ $self->{PIPES} }, $io;
2561 }
2562  
2563 ## Put filters on the end of the filter chains to read & write the pipes.
2564 ## Clear pipe states
2565 1432 for my $pipe ( @{ $self->{PIPES} } ) {
2566 2071 $pipe->{SOURCE_EMPTY} = 0;
2567 2071 $pipe->{PAUSED} = 0;
2568 2071 ▶ if ( $pipe->{TYPE} =~ /^>/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pipe->{'TYPE'} =~ /^>/) { } 1448 623 2071
2569 my $pipe_reader = sub {
2570 2623 ▶ my ( undef, $out_ref ) = @_;
Subroutine __ANON__: called CC=11 SCAR=27.6
2571  
2572 2623 ▶ return undef unless defined $pipe->{FD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pipe->{"FD"} 0 2623 2623
2573 2623 ▶ return 0 unless vec( $self->{ROUT}, $pipe->{FD}, 1 );
Branch: 1 branch
BranchTrueFalseTotal
unless vec $self->{"ROUT"}, $pipe->{"FD"}, 1 0 2623 2623
2574  
2575 2623 vec( $self->{ROUT}, $pipe->{FD}, 1 ) = 0;
2576  
2577 2623 ▶ _debug_desc_fd( 'reading from', $pipe ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2623 2623
2578 2623 my $in = eval { _read( $pipe->{FD} ) };
2579 2623 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 6 2617 2623
2580 6 $in = '';
2581 ## IO::Pty throws the Input/output error if the kid dies.
2582 ## read() throws the bad file descriptor message if the
2583 ## kid dies on Win32.
2584 6 ▶ die $@
Branch: 1 branch
BranchTrueFalseTotal
unless $@ =~ /$IPC::Run::_EIO/ or $@ =~ /input or output/ and $^O =~ /aix/ or &Win32_MODE() and $@ =~ /Bad file descriptor/ 0 6 6
Condition16%2/12
$@ =~ /$IPC::Run::_EIO/ or $@ =~ /input or output/ and $^O =~ /aix/ or &Win32_MODE() and $@ =~ /Bad file descriptor/
l!l&&r!l&&!r
600
$@ =~ /$IPC::Run::_EIO/ or $@ =~ /input or output/ and $^O =~ /aix/
l!l&&r!l&&!r
600
$@ =~ /input or output/ and $^O =~ /aix/
!ll&&!rl&&r
000
&Win32_MODE() and $@ =~ /Bad file descriptor/
!ll&&!rl&&r
000
MC/DC0%0/5
$@ =~ /$IPC::Run::_EIO/ or $@ =~ /input or output/ and $^O =~ /aix/ or &Win32_MODE() and $@ =~ /Bad file descriptor/
$@ =~ /$IPC::Run::_EIO/ $@ =~ /input or output/ $^O =~ /aix/ &Win32_MODE() $@ =~ /Bad file descriptor/
Truth table12%1/8
A or B and C or D and E
A= $@ =~ /$IPC::Run::_EIO/B= $@ =~ /input or output/C= $^O =~ /aix/D= &Win32_MODE()E= $@ =~ /Bad file descriptor/
ABCDEresult
1XXXX1
011XX1
00X111
010111
00X0X0
00X100
0100X0
010100
2585 unless $@ =~ $_EIO
2586 || ( $@ =~ /input or output/ && $^O =~ /aix/ )
2587 || ( Win32_MODE && $@ =~ /Bad file descriptor/ );
2588 }
2589  
2590 2623 ▶ unless ( length $in ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $in) 1273 1350 2623
2591 1273 $self->_clobber($pipe);
2592 1273 return undef;
2593 }
2594  
2595 ## Protect the position so /.../g matches may be used.
2596 1350 my $pos = pos $$out_ref;
2597 1350 $$out_ref .= $in;
2598 1350 pos($$out_ref) = $pos;
2599 1350 return 1;
2600 1448 };
2601 ## Input filters are the last filters
2602 1448 push @{ $pipe->{FILTERS} }, $pipe_reader;
2603 1448 push @{ $self->{TEMP_FILTERS} }, $pipe_reader;
2604 }
2605 else {
2606 my $pipe_writer = sub {
2607 2142 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=12 SCAR=25.3
2608 2142 ▶ return undef unless defined $pipe->{FD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pipe->{"FD"} 0 2142 2142
2609 return 0
2610 unless vec( $self->{WOUT}, $pipe->{FD}, 1 )
2611 2142 ▶ || $pipe->{PAUSED};
Branch: 1 branch
BranchTrueFalseTotal
unless vec $self->{"WOUT"}, $pipe->{"FD"}, 1 or $pipe->{"PAUSED"} 0 2142 2142
Condition66%2/3
vec $self->{"WOUT"}, $pipe->{"FD"}, 1 or $pipe->{"PAUSED"}
l!l&&r!l&&!r
89012520
MC/DC0%0/2
vec $self->{"WOUT"}, $pipe->{"FD"}, 1 or $pipe->{"PAUSED"}
vec $self->{"WOUT"}, $pipe->{"FD"}, 1 $pipe->{"PAUSED"}
Truth table66%2/3
A or B
A= vec $self->{"WOUT"}, $pipe->{"FD"}, 1B= $pipe->{"PAUSED"}
ABresult
1X1
011
000
2612  
2613 2142 vec( $self->{WOUT}, $pipe->{FD}, 1 ) = 0;
2614  
2615 2142 ▶ if ( !length $$in_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $$in_ref) 2142 0 2142
2616 2142 ▶ if ( !defined get_more_input ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined &get_more_input()) 531 1611 2142
2617 531 $self->_clobber($pipe);
2618 531 return undef;
2619 }
2620 }
2621  
2622 1611 ▶ unless ( length $$in_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $$in_ref) 1211 400 1611
2623 1211 ▶ unless ( $pipe->{PAUSED} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pipe->{"PAUSED"}) 69 1142 1211
2624 69 ▶ _debug_desc_fd( 'pausing', $pipe ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 69 69
2625 69 vec( $self->{WIN}, $pipe->{FD}, 1 ) = 0;
2626  
2627 # vec( $self->{EIN}, $pipe->{FD}, 1 ) = 0;
2628 69 vec( $self->{PIN}, $pipe->{FD}, 1 ) = 1;
2629 69 $pipe->{PAUSED} = 1;
2630 }
2631 1211 return 0;
2632 }
2633 400 ▶ _debug_desc_fd( 'writing to', $pipe ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 400 400
2634  
2635 400 ▶ if ( length $$in_ref && $$in_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $$in_ref and $$in_ref) { } 394 6 400
Condition66%2/3
length $$in_ref and $$in_ref
!ll&&!rl&&r
06394
MC/DC50%1/2
length $$in_ref and $$in_ref
length $$in_ref $$in_ref
Truth table66%2/3
A and B
A= length $$in_refB= $$in_ref
ABresult
0X0
100
111
2636 394 my $c = _write( $pipe->{FD}, $$in_ref );
2637 394 substr( $$in_ref, 0, $c, '' );
2638 }
2639 else {
2640 6 $self->_clobber($pipe);
2641 6 return undef;
2642 }
2643  
2644 394 return 1;
2645 623 };
2646 ## Output filters are the first filters
2647 623 unshift @{ $pipe->{FILTERS} }, $pipe_writer;
2648 623 push @{ $self->{TEMP_FILTERS} }, $pipe_writer;
2649 }
2650 }
2651 }
2652  
2653 sub _dup2_gently {
2654 ## A METHOD, NOT A FUNCTION, NEEDS $self!
2655 202 ▶ my IPC::Run $self = shift;
Subroutine _dup2_gently: called CC=6 SCAR=19.1
2656 202 my ( $files, $fd1, $fd2 ) = @_;
2657 ## Moves TFDs that are using the destination fd out of the
2658 ## way before calling _dup2
2659 202 for (@$files) {
2660 556 ▶ next unless defined $_->{TFD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_->{"TFD"} 43 513 556
2661 513 ▶ $_->{TFD} = _dup( $_->{TFD} ) if $_->{TFD} == $fd2;
Branch: 1 branch
BranchTrueFalseTotal
if $_->{"TFD"} == $fd2 3 510 513
2662 }
2663 202 ▶ if ( defined $self->{DEBUG_FD} && $self->{DEBUG_FD} == $fd2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"DEBUG_FD"} and $self->{"DEBUG_FD"} == $fd2) 0 202 202
Condition33%1/3
defined $self->{"DEBUG_FD"} and $self->{"DEBUG_FD"} == $fd2
!ll&&!rl&&r
20200
MC/DC0%0/2
defined $self->{"DEBUG_FD"} and $self->{"DEBUG_FD"} == $fd2
defined $self->{"DEBUG_FD"} $self->{"DEBUG_FD"} == $fd2
Truth table33%1/3
A and B
A= defined $self->{"DEBUG_FD"}B= $self->{"DEBUG_FD"} == $fd2
ABresult
0X0
100
111
2664 0 $self->{DEBUG_FD} = _dup $self->{DEBUG_FD};
2665 0 $fds{$self->{DEBUG_FD}}{needed} = 1;
2666 }
2667 202 _dup2_rudely( $fd1, $fd2 );
2668 }
2669  
2670 =pod
2671  
2672 =item close_terminal
2673  
2674 This is used as (or in) an init sub to cast off the bonds of a controlling
2675 terminal. It must precede all other redirection ops that affect
2676 STDIN, STDOUT, or STDERR to be guaranteed effective.
2677  
2678 =cut
2679  
2680 sub close_terminal {
2681 ## Cast of the bonds of a controlling terminal
2682  
2683 # Just in case the parent (I'm talking to you FCGI) had these tied.
2684 4 ▶ untie *STDIN;
Subroutine close_terminal: called CC=3 SCAR=11.1
Pod documented
2685 4 untie *STDOUT;
2686 4 untie *STDERR;
2687  
2688 4 ▶ POSIX::setsid() || croak "POSIX::setsid() failed";
Branch: 1 branch
BranchTrueFalseTotal
POSIX::setsid() or croak("POSIX::setsid() failed") 0 4 4
2689 4 ▶ _debug "closing stdin, out, err"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 4 4
2690 if _debugging_details;
2691 4 close STDIN;
2692 4 close STDERR;
2693 4 close STDOUT;
2694 }
2695  
2696 sub _do_kid_and_exit {
2697 101 ▶ my IPC::Run $self = shift;
Subroutine _do_kid_and_exit: called CC=36 SCAR=40.6
2698 101 my ($kid) = @_;
2699  
2700 101 my ( $s1, $s2 );
2701 101 ▶ if ( $] < 5.008 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.008") 0 101 101
2702 ## For unknown reasons, placing these two statements in the eval{}
2703 ## causes the eval {} to not catch errors after they are executed in
2704 ## perl 5.6.0, godforsaken version that it is...not sure about 5.6.1.
2705 ## Part of this could be that these symbols get destructed when
2706 ## exiting the eval, and that destruction might be what's (wrongly)
2707 ## confusing the eval{}, allowing the exception to propagate.
2708 0 $s1 = Symbol::gensym();
2709 0 $s2 = Symbol::gensym();
2710 }
2711  
2712 101 eval {
2713 101 local $cur_self = $self;
2714  
2715 101 ▶ if (_debugging) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging()) 0 101 101
2716 _set_child_debug_name(
2717 ref $kid->{VAL} eq "CODE"
2718 ? "CODE"
2719 0 ▶ : basename( $kid->{VAL}->[0] )
Branch: 1 branch
BranchTrueFalseTotal
ref $kid->{'VAL'} eq 'CODE' ? : 0 0 0
2720 );
2721 }
2722  
2723 ## close parent FD's first so they're out of the way.
2724 ## Don't close STDIN, STDOUT, STDERR: they should be inherited or
2725 ## overwritten below.
2726 65 do { $_->{needed} = 1 for @fds{0..2} }
2727 101 ▶ unless $self->{noinherit};
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"noinherit"}) 65 36 101
2728  
2729 101 $fds{$self->{SYNC_WRITER_FD}}{needed} = 1;
2730 101 ▶ $fds{$self->{DEBUG_FD}}{needed} = 1 if defined $self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"DEBUG_FD"} 0 101 101
2731  
2732 $fds{$_->{TFD}}{needed} = 1
2733 101 foreach grep { defined $_->{TFD} } @{$kid->{OPS} };
2734  
2735  
2736 ## TODO: use the forthcoming IO::Pty to close the terminal and
2737 ## make the first pty for this child the controlling terminal.
2738 ## This will also make it so that pty-laden kids don't cause
2739 ## other kids to lose stdin/stdout/stderr.
2740  
2741 101 ▶ if ( %{ $self->{PTYS} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$self->{"PTYS"};}) 4 97 101
2742 ## Clean up the parent's fds.
2743 4 for ( keys %{ $self->{PTYS} } ) {
2744 4 ▶ _debug "Cleaning up parent's ptty '$_'" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 4 4
2745 4 $self->{PTYS}->{$_}->make_slave_controlling_terminal;
2746 4 my $slave = $self->{PTYS}->{$_}->slave;
2747 4 delete $fds{$self->{PTYS}->{$_}->fileno};
2748 4 close $self->{PTYS}->{$_};
2749 4 $self->{PTYS}->{$_} = $slave;
2750 }
2751  
2752 4 close_terminal;
2753 4 delete @fds{0..2};
2754 }
2755  
2756 101 for my $sibling ( @{ $self->{KIDS} } ) {
2757 117 for ( @{ $sibling->{OPS} } ) {
2758 231 ▶ if ( $_->{TYPE} =~ /^.pty.$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{"TYPE"} =~ /^.pty.$/) 5 226 231
2759 5 $_->{TFD} = $self->{PTYS}->{ $_->{PTY_ID} }->fileno;
2760 5 $fds{$_->{TFD}}{needed} = 1;
2761 }
2762  
2763 # for ( $_->{FD}, ( $sibling != $kid ? $_->{TFD} : () ) ) {
2764 # if ( defined $_ && ! $closed[$_] && ! $needed[$_] ) {
2765 # _close( $_ );
2766 # $closed[$_] = 1;
2767 # $_ = undef;
2768 # }
2769 # }
2770 }
2771 }
2772  
2773 ## This is crude: we have no way of keeping track of browsing all open
2774 ## fds, so we scan to a fairly high fd.
2775 101 ▶ _debug "open fds: ", join " ", keys %fds if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 101 101
2776  
2777 101 _close( $_ ) foreach grep { ! $fds{$_}{needed} } keys %fds;
2778  
2779 101 for ( @{ $kid->{OPS} } ) {
2780 208 ▶ if ( defined $_->{TFD} ) {
Branch: 4 branches
BranchTrueFalseTotal
if (defined $_->{'TFD'}) { } 193 15 208
elsif ($_->{'TYPE'} eq 'dup') { } 9 6 15
elsif ($_->{'TYPE'} eq 'close') { } 5 1 6
elsif ($_->{'TYPE'} eq 'init') { } 1 0 1
2781  
2782 # we're always creating KFD
2783 193 $fds{$_->{KFD}}{needed} = 1;
2784  
2785 193 ▶ unless ( $_->{TFD} == $_->{KFD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{'TFD'} == $_->{'KFD'}) { } 1 192 193
2786 192 $self->_dup2_gently( $kid->{OPS}, $_->{TFD}, $_->{KFD} );
2787 192 $fds{$_->{TFD}}{lazy_close} = 1;
2788 } else {
2789 1 my $fd = _dup($_->{TFD});
2790 1 $self->_dup2_gently( $kid->{OPS}, $fd, $_->{KFD} );
2791 1 _close($fd);
2792 }
2793 }
2794 elsif ( $_->{TYPE} eq 'dup' ) {
2795 $self->_dup2_gently( $kid->{OPS}, $_->{KFD1}, $_->{KFD2} )
2796 9 ▶ unless $_->{KFD1} == $_->{KFD2};
Branch: 1 branch
BranchTrueFalseTotal
unless $_->{"KFD1"} == $_->{"KFD2"} 9 0 9
2797 9 $fds{$_->{KFD2}}{needed} = 1;
2798 }
2799 elsif ( $_->{TYPE} eq 'close' ) {
2800 5 for ( $_->{KFD} ) {
2801 5 ▶ if ( $fds{$_} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fds{$_}) 4 1 5
2802 4 _close($_);
2803 4 $_ = undef;
2804 }
2805 }
2806 }
2807 elsif ( $_->{TYPE} eq 'init' ) {
2808 1 $_->{SUB}->();
2809 }
2810 }
2811  
2812 101 _close( $_ ) foreach grep { $fds{$_}{lazy_close} } keys %fds;
2813  
2814 101 ▶ if ( ref $kid->{VAL} ne 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $kid->{"VAL"} ne "CODE") 99 2 101
2815 99 ▶ open $s1, ">&=$self->{SYNC_WRITER_FD}"
Branch: 1 branch
BranchTrueFalseTotal
open $s1, qq[>&=$self->{"SYNC_WRITER_FD"}] or croak("$! setting filehandle to fd SYNC_WRITER_FD") 0 99 99
2816 or croak "$! setting filehandle to fd SYNC_WRITER_FD";
2817 99 fcntl $s1, F_SETFD, 1;
2818  
2819 99 ▶ if ( defined $self->{DEBUG_FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"DEBUG_FD"}) 0 99 99
2820 0 ▶ open $s2, ">&=$self->{DEBUG_FD}"
Branch: 1 branch
BranchTrueFalseTotal
open $s2, qq[>&=$self->{"DEBUG_FD"}] or croak("$! setting filehandle to fd DEBUG_FD") 0 0 0
2821 or croak "$! setting filehandle to fd DEBUG_FD";
2822 0 fcntl $s2, F_SETFD, 1;
2823 }
2824  
2825 99 ▶ if (_debugging) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging()) 0 99 99
2826 0 my @cmd = ( $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ] );
2827 0 ▶ _debug 'execing ', join " ", map { /[\s\"]/ ? "'$_'" : $_ } @cmd;
Branch: 1 branch
BranchTrueFalseTotal
/[\s\"]/ ? : 0 0 0
2828 }
2829  
2830 die "exec failed: simulating exec() failure"
2831 99 ▶ if $self->{_simulate_exec_failure};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_simulate_exec_failure"} 0 99 99
2832  
2833 99 _exec $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ];
2834  
2835 0 croak "exec failed: $!";
2836 }
2837 };
2838 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
2839 0 _write $self->{SYNC_WRITER_FD}, $@;
2840 ## Avoid DESTROY.
2841 0 POSIX::_exit(1);
2842 }
2843  
2844 ## We must be executing code in the child, otherwise exec() would have
2845 ## prevented us from being here.
2846 2 _close $self->{SYNC_WRITER_FD};
2847 2 ▶ _debug 'calling fork()ed CODE ref' if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 2 2
2848 2 ▶ POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"DEBUG_FD"} 0 2 2
2849 ## TODO: Overload CORE::GLOBAL::exit...
2850 2 $kid->{VAL}->();
2851  
2852 ## There are bugs in perl closures up to and including 5.6.1
2853 ## that may keep this next line from having any effect, and it
2854 ## won't have any effect if our caller has kept a copy of it, but
2855 ## this may cause the closure to be cleaned up. Maybe.
2856 0 $kid->{VAL} = undef;
2857  
2858 ## Use POSIX::_exit to avoid global destruction, since this might
2859 ## cause DESTROY() to be called on objects created in the parent
2860 ## and thus cause double cleanup. For instance, if DESTROY() unlinks
2861 ## a file in the child, we don't want the parent to suddenly miss
2862 ## it.
2863 0 POSIX::_exit(0);
2864 }
2865  
2866 =pod
2867  
2868 =item start
2869  
2870 $h = start(
2871 \@cmd, \$in, \$out, ...,
2872 timeout( 30, name => "process timeout" ),
2873 $stall_timeout = timeout( 10, name => "stall timeout" ),
2874 );
2875  
2876 $h = start \@cmd, '<', \$in, '|', \@cmd2, ...;
2877  
2878 start() accepts a harness or harness specification and returns a harness
2879 after building all of the pipes and launching (via fork()/exec(), or, maybe
2880 someday, spawn()) all the child processes. It does not send or receive any
2881 data on the pipes, see pump() and finish() for that.
2882  
2883 You may call harness() and then pass its result to start() if you like,
2884 but you only need to if it helps you structure or tune your application.
2885 If you do call harness(), you may skip start() and proceed directly to
2886 pump.
2887  
2888 start() also starts all timers in the harness. See L<IPC::Run::Timer>
2889 for more information.
2890  
2891 start() flushes STDOUT and STDERR to help you avoid duplicate output.
2892 It has no way of asking Perl to flush all your open filehandles, so
2893 you are going to need to flush any others you have open. Sorry.
2894  
2895 Here's how if you don't want to alter the state of $| for your
2896 filehandle:
2897  
2898 $ofh = select HANDLE; $of = $|; $| = 1; $| = $of; select $ofh;
2899  
2900 If you don't mind leaving output unbuffered on HANDLE, you can do
2901 the slightly shorter
2902  
2903 $ofh = select HANDLE; $| = 1; select $ofh;
2904  
2905 Or, you can use IO::Handle's flush() method:
2906  
2907 use IO::Handle;
2908 flush HANDLE;
2909  
2910 Perl needs the equivalent of C's fflush( (FILE *)NULL ).
2911  
2912 =cut
2913  
2914 sub start {
2915  
2916 # $SIG{__DIE__} = sub { my $s = shift; Carp::cluck $s; die $s };
2917 1558 ▶ my $options;
Subroutine start: called CC=46 SCAR=48.4
Pod documented
2918 1558 ▶ if ( @_ && ref $_[-1] eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ref $_[-1] eq "HASH") 0 1558 1558
Condition33%1/3
@_ and ref $_[-1] eq "HASH"
!ll&&!rl&&r
015580
MC/DC0%0/2
@_ and ref $_[-1] eq "HASH"
@_ ref $_[-1] eq "HASH"
Truth table33%1/3
A and B
A= @_B= ref $_[-1] eq "HASH"
ABresult
0X0
100
111
2919 0 $options = pop;
2920 0 require Data::Dumper;
2921 0 carp "Passing in options as a hash is deprecated:\n", Data::Dumper::Dumper($options);
2922 }
2923  
2924 1558 my IPC::Run $self;
2925 1558 ▶ if ( @_ == 1 && UNIVERSAL::isa( $_[0], __PACKAGE__ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__)) { } 28 1530 1558
Condition100%3/3
@_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__)
!ll&&!rl&&r
142410628
MC/DC100%2/2
@_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__)
@_ == 1 UNIVERSAL::isa($_[0], __PACKAGE__)
Truth table100%3/3
A and B
A= @_ == 1B= UNIVERSAL::isa($_[0], __PACKAGE__)
ABresult
0X0
100
111
2926 28 $self = shift;
2927 28 $self->{$_} = $options->{$_} for keys %$options;
2928 }
2929 else {
2930 1530 ▶ $self = harness( @_, $options ? $options : () );
Branch: 1 branch
BranchTrueFalseTotal
$options ? : 0 1530 1530
2931 }
2932  
2933 1481 local $cur_self = $self;
2934  
2935 1481 ▶ $self->kill_kill if $self->{STATE} == _started;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"STATE"} == 3 4 1477 1481
2936  
2937 1481 ▶ _debug "** starting" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 1481 1481
2938  
2939 1481 $_->{RESULT} = undef for @{ $self->{KIDS} };
2940  
2941 ## Assume we're not being called from &run. It will correct our
2942 ## assumption if need be. This affects whether &_select_loop clears
2943 ## input queues to '' when they're empty.
2944 1481 $self->{clear_ins} = 1;
2945  
2946 1481 ▶ IPC::Run::Win32Helper::optimize $self
Branch: 1 branch
BranchTrueFalseTotal
if &Win32_MODE() and $IPC::Run::in_run 0 1481 1481
Condition33%1/3
&Win32_MODE() and $IPC::Run::in_run
!ll&&!rl&&r
148100
MC/DC0%0/2
&Win32_MODE() and $IPC::Run::in_run
&Win32_MODE() $IPC::Run::in_run
Truth table33%1/3
A and B
A= &Win32_MODE()B= $IPC::Run::in_run
ABresult
0X0
100
111
2947 if Win32_MODE && $in_run;
2948  
2949 1481 my @errs;
2950  
2951 1481 for ( @{ $self->{TIMERS} } ) {
2952 18 eval { $_->start };
2953 18 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 18 18
2954 0 push @errs, $@;
2955 0 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
2956 }
2957 }
2958  
2959 1481 eval { $self->_open_pipes };
2960 1481 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 49 1432 1481
2961 49 push @errs, $@;
2962 49 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 49 49
2963 }
2964  
2965 1481 ▶ if ( !@errs ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@errs) 1432 49 1481
2966 ## This is a bit of a hack, we should do it for all open filehandles.
2967 ## Since there's no way I know of to enumerate open filehandles, we
2968 ## autoflush STDOUT and STDERR. This is done so that the children don't
2969 ## inherit output buffers chock full o' redundant data. It's really
2970 ## confusing to track that down.
2971 1432 { my $ofh = select STDOUT; my $of = $|; $| = 1; $| = $of; select $ofh; }
2972 1432 { my $ofh = select STDERR; my $of = $|; $| = 1; $| = $of; select $ofh; }
2973 1432 for my $kid ( @{ $self->{KIDS} } ) {
2974 1457 $kid->{RESULT} = undef;
2975 _debug "child: ", _debugstrings( $kid->{VAL} )
2976 1457 ▶ if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1457 1457
2977 1457 eval {
2978 croak "simulated failure of fork"
2979 1457 ▶ if $self->{_simulate_fork_failure};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_simulate_fork_failure"} 7 1450 1457
2980 1450 ▶ unless (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 1450 1450
2981 1450 $self->_spawn($kid);
2982 }
2983 else {
2984 ## TODO: Test and debug spawning code. Someday.
2985 _debug(
2986 'spawning ',
2987 _debugstrings(
2988 [
2989 $kid->{PATH},
2990 0 @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ]
2991 ]
2992 )
2993 0 ▶ ) if $kid->{PATH} && _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if $kid->{"PATH"} and &_debugging() 0 0 0
Condition0%0/3
$kid->{"PATH"} and &_debugging()
!ll&&!rl&&r
000
MC/DC0%0/2
$kid->{"PATH"} and &_debugging()
$kid->{"PATH"} &_debugging()
Truth table0%0/3
A and B
A= $kid->{"PATH"}B= &_debugging()
ABresult
0X0
100
111
2994 ## The external kid wouldn't know what to do with it anyway.
2995 ## This is only used by the "helper" pump processes on Win32.
2996 0 _dont_inherit( $self->{DEBUG_FD} );
2997 ( $kid->{PID}, $kid->{PROCESS} ) = IPC::Run::Win32Helper::win32_spawn(
2998 ref( $kid->{VAL} ) eq "ARRAY"
2999 0 ? [ $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ] ]
3000 : $kid->{VAL},
3001 $kid->{OPS},
3002 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
ref $kid->{'VAL'} eq 'ARRAY' ? : 0 0 0
3003 0 ▶ _debug "spawn() = ", $kid->{PID} if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3004 0 ▶ if ($self->{_sleep_after_win32_spawn}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_sleep_after_win32_spawn"}) 0 0 0
3005 0 sleep $self->{_sleep_after_win32_spawn};
3006 0 ▶ _debug "after sleep $self->{_sleep_after_win32_spawn}"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3007 if _debugging;
3008 }
3009 }
3010 };
3011 1356 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 9 1347 1356
3012 9 push @errs, $@;
3013 9 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 9 9
3014 }
3015 }
3016 }
3017  
3018 ## Close all those temporary filehandles that the kids needed.
3019 1380 for my $pty ( values %{ $self->{PTYS} } ) {
3020 10 close $pty->slave;
3021 }
3022  
3023 1380 my @closed;
3024 1380 for my $kid ( @{ $self->{KIDS} } ) {
3025 1397 for ( @{ $kid->{OPS} } ) {
3026 2487 my $close_it = eval {
3027 defined $_->{TFD}
3028 && !$_->{DONT_CLOSE}
3029 && !$closed[ $_->{TFD} ]
3030 && ( !Win32_MODE || !$_->{RECV_THROUGH_TEMP_FILE} ) ## Win32 hack
3031 2487 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
defined $_->{"TFD"} and not $_->{"DONT_CLOSE"} and not $closed[$_->{"TFD"}] and not &Win32_MODE() && $_->{"RECV_THROUGH_TEMP_FILE"} 2136 351 2487
Condition66%8/12
defined $_->{'TFD'} && !$_->{'DONT_CLOSE'} && !$closed[$_->{'TFD'}] && !(&Win32_MODE() && $_->{'RECV_THROUGH_TEMP_FILE'})
!ll&&!rl&&r
35102136
defined $_->{"TFD"} and not $_->{"DONT_CLOSE"} and not $closed[$_->{"TFD"}]
!ll&&!rl&&r
35102136
defined $_->{"TFD"} and not $_->{"DONT_CLOSE"}
!ll&&!rl&&r
2461052136
&Win32_MODE() && $_->{'RECV_THROUGH_TEMP_FILE'}
!ll&&!rl&&r
213600
MC/DC40%2/5
defined $_->{'TFD'} && !$_->{'DONT_CLOSE'} && !$closed[$_->{'TFD'}] && !(&Win32_MODE() && $_->{'RECV_THROUGH_TEMP_FILE'})
defined $_->{"TFD"} not $_->{"DONT_CLOSE"} not $closed[$_->{"TFD"}] &Win32_MODE() $_->{'RECV_THROUGH_TEMP_FILE'}
Truth table50%3/6
A and not(B) and not(C) && not(D && E)
A= defined $_->{"TFD"}B= not $_->{"DONT_CLOSE"}C= not $closed[$_->{"TFD"}]D= &Win32_MODE()E= $_->{'RECV_THROUGH_TEMP_FILE'}
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
3032 2487 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2487 2487
3033 0 push @errs, $@;
3034 0 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3035 }
3036 2487 ▶ if ( $close_it || $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($close_it or $@) 2136 351 2487
Condition66%2/3
$close_it or $@
l!l&&r!l&&!r
21360351
MC/DC50%1/2
$close_it or $@
$close_it $@
Truth table66%2/3
A or B
A= $close_itB= $@
ABresult
1X1
011
000
3037 2136 eval {
3038 2136 _close( $_->{TFD} );
3039 2136 $closed[ $_->{TFD} ] = 1;
3040 2136 $_->{TFD} = undef;
3041 };
3042 2136 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2136 2136
3043 0 push @errs, $@;
3044 0 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3045 }
3046 }
3047 }
3048 }
3049 1380 ▶ confess "gak!" unless defined $self->{PIPES};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"PIPES"} 0 1380 1380
3050  
3051 1380 ▶ if (@errs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@errs) 58 1322 1380
3052 58 eval { $self->_cleanup };
3053 58 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 58 58
3054 58 die join( '', @errs );
3055 }
3056  
3057 1322 $self->{STATE} = _started;
3058 1322 return $self;
3059 }
3060  
3061 =item adopt
3062  
3063 Experimental feature. NOT FUNCTIONAL YET, NEED TO CLOSE FDS BETTER IN CHILDREN. SEE t/adopt.t for a test suite.
3064  
3065 =cut
3066  
3067 sub adopt {
3068 0 ▶ my IPC::Run $self = shift;
Subroutine adopt: not called CC=3 SCAR=24.8
Pod documented
3069  
3070 0 for my $adoptee (@_) {
3071 0 push @{ $self->{IOS} }, @{ $adoptee->{IOS} };
3072 ## NEED TO RENUMBER THE KIDS!!
3073 0 push @{ $self->{KIDS} }, @{ $adoptee->{KIDS} };
3074 0 push @{ $self->{PIPES} }, @{ $adoptee->{PIPES} };
3075 0 $self->{PTYS}->{$_} = $adoptee->{PTYS}->{$_} for keys %{ $adoptee->{PYTS} };
3076 0 push @{ $self->{TIMERS} }, @{ $adoptee->{TIMERS} };
3077 0 $adoptee->{STATE} = _finished;
3078 }
3079 }
3080  
3081 sub _clobber {
3082 1848 ▶ my IPC::Run $self = shift;
Subroutine _clobber: called CC=11 SCAR=24.3
3083 1848 my ($file) = @_;
3084 1848 ▶ _debug_desc_fd( "closing", $file ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1848 1848
3085 1848 my $doomed = $file->{FD};
3086 1848 ▶ my $dir = $file->{TYPE} =~ /^</ ? 'WIN' : 'RIN';
Branch: 1 branch
BranchTrueFalseTotal
$file->{'TYPE'} =~ /^</ ? : 552 1296 1848
3087 1848 vec( $self->{$dir}, $doomed, 1 ) = 0;
3088  
3089 # vec( $self->{EIN}, $doomed, 1 ) = 0;
3090 1848 vec( $self->{PIN}, $doomed, 1 ) = 0;
3091 1848 ▶ if ( $file->{TYPE} =~ /^(.)pty.$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($file->{'TYPE'} =~ /^(.)pty.$/) { } 11 1837 1848
elsif (UNIVERSAL::isa($file, 'IPC::Run::IO')) { } 1837 0 1837
3092 11 ▶ if ( $1 eq '>' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($1 eq ">") 6 5 11
3093 ## Only close output ptys. This is so that ptys as inputs are
3094 ## never autoclosed, which would risk losing data that was
3095 ## in the slave->parent queue.
3096 6 ▶ _debug_desc_fd "closing pty", $file if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 6 6
3097 close $self->{PTYS}->{ $file->{PTY_ID} }
3098 6 ▶ if defined $self->{PTYS}->{ $file->{PTY_ID} };
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"PTYS"}{$file->{"PTY_ID"}} 6 0 6
3099 6 $self->{PTYS}->{ $file->{PTY_ID} } = undef;
3100 }
3101 }
3102 elsif ( UNIVERSAL::isa( $file, 'IPC::Run::IO' ) ) {
3103 1837 ▶ $file->close unless $file->{DONT_CLOSE};
Branch: 1 branch
BranchTrueFalseTotal
unless $file->{"DONT_CLOSE"} 1837 0 1837
3104 }
3105 else {
3106 0 _close($doomed);
3107 }
3108  
3109 1848 @{ $self->{PIPES} } = grep
3110 defined $_->{FD} && ( $_->{TYPE} ne $file->{TYPE} || $_->{FD} ne $doomed ),
3111 1848 ▶ @{ $self->{PIPES} };
Condition100%6/6
defined $_->{'FD'} && ($_->{'TYPE'} ne $file->{'TYPE'} || $_->{'FD'} ne $doomed)
!ll&&!rl&&r
1869111310
$_->{"TYPE"} ne $file->{"TYPE"} or $_->{"FD"} ne $doomed
l!l&&r!l&&!r
83247811
MC/DC100%3/3
defined $_->{'FD'} && ($_->{'TYPE'} ne $file->{'TYPE'} || $_->{'FD'} ne $doomed)
defined $_->{'FD'} $_->{"TYPE"} ne $file->{"TYPE"} $_->{"FD"} ne $doomed
Truth table100%4/4
A && B or C
A= defined $_->{'FD'}B= $_->{"TYPE"} ne $file->{"TYPE"}C= $_->{"FD"} ne $doomed
ABCresult
0XX0
1000
11X1
1011
3112  
3113 1848 $file->{FD} = undef;
3114 }
3115  
3116 sub _select_loop {
3117 1831 ▶ my IPC::Run $self = shift;
Subroutine _select_loop: called CC=71 SCAR=67.0
3118  
3119 # With !defined $SIG{CHLD} (the default), Perl restarts any select() that
3120 # SIGCHLD interrupts. Install a no-op handler, to make select() terminate
3121 # with EINTR, accelerating our reaction. This doesn't help if SIGCHLD
3122 # arrives just before the select() call; https://cr.yp.to/docs/selfpipe.html
3123 # is a way to close that race condition. It doesn't help on Windows, where
3124 # we substitute a low timeout in zero-FD (timeout-only) select(). That
3125 # spends CPU to achieve responsiveness. We could do better there with a
3126 # C-language module that calls OpenProcess(), WSAEventSelect(), and
3127 # WaitForMultipleObjects().
3128 #
3129 # If non-IPC::Run code has installed a handler, via $SIG{CHLD} assignment or
3130 # via POSIX::sigaction(), this statement takes no action, and the existing
3131 # handler helps just like this one would. The cap on $not_forever helps
3132 # when non-IPC::Run code has blocked SIGCHLD, e.g. via POSIX::sigprocmask().
3133 ▶ local $SIG{CHLD} = sub { }
Subroutine __ANON__: called CC=1 SCAR=0.0
3134 1831 ▶ unless defined $SIG{CHLD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $SIG{"CHLD"} 1831 0 1831
3135  
3136 1831 my $io_occurred;
3137  
3138 1831 my $min_select_timeout = 0.01;
3139 1831 my $not_forever = $min_select_timeout;
3140  
3141 SELECT:
3142 1831 ▶ while ( $self->pumpable ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->pumpable) 7740 911 8651
3143 7740 ▶ if ( $io_occurred && $self->{break_on_io} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($io_occurred and $self->{"break_on_io"}) 210 7530 7740
Condition100%3/3
$io_occurred and $self->{"break_on_io"}
!ll&&!rl&&r
50882442210
MC/DC100%2/2
$io_occurred and $self->{"break_on_io"}
$io_occurred $self->{"break_on_io"}
Truth table100%3/3
A and B
A= $io_occurredB= $self->{"break_on_io"}
ABresult
0X0
100
111
3144 210 ▶ _debug "exiting _select(): io occurred and break_on_io set"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 210 210
3145 if _debugging_details;
3146 210 last;
3147 }
3148  
3149 7530 ▶ my $timeout = $self->{non_blocking} ? 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'non_blocking'} ? : 707 6823 7530
3150  
3151 7530 ▶ if ( @{ $self->{TIMERS} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"TIMERS"};}) 193 7337 7530
3152 193 my $now = time;
3153 193 my $time_left;
3154 193 for ( @{ $self->{TIMERS} } ) {
3155 193 ▶ next unless $_->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $_->is_running 0 193 193
3156 193 $time_left = $_->check($now);
3157 ## Return when a timer expires
3158 183 ▶ return if defined $time_left && !$time_left;
Branch: 1 branch
BranchTrueFalseTotal
if defined $time_left and not $time_left 0 183 183
Condition33%1/3
defined $time_left and not $time_left
!ll&&!rl&&r
01830
MC/DC0%0/2
defined $time_left and not $time_left
defined $time_left not $time_left
Truth table33%1/3
A and not(B)
A= defined $time_leftB= not $time_left
ABresult
0X0
100
111
3159 183 ▶ $timeout = $time_left
Branch: 1 branch
BranchTrueFalseTotal
if not defined $timeout or $time_left < $timeout 82 101 183
Condition66%2/3
not defined $timeout or $time_left < $timeout
l!l&&r!l&&!r
820101
MC/DC50%1/2
not defined $timeout or $time_left < $timeout
not defined $timeout $time_left < $timeout
Truth table66%2/3
not(A) or B
A= not defined $timeoutB= $time_left < $timeout
ABresult
1X1
011
000
3160 if !defined $timeout || $time_left < $timeout;
3161 }
3162 }
3163  
3164 ##
3165 ## See if we can unpause any input channels
3166 ##
3167 7520 my $paused = 0;
3168  
3169 7520 for my $file ( @{ $self->{PIPES} } ) {
3170 13067 ▶ next unless $file->{PAUSED} && $file->{TYPE} =~ /^</;
Branch: 1 branch
BranchTrueFalseTotal
unless $file->{"PAUSED"} and $file->{"TYPE"} =~ /^</ 11876 1191 13067
Condition66%2/3
$file->{"PAUSED"} and $file->{"TYPE"} =~ /^</
!ll&&!rl&&r
1187601191
MC/DC50%1/2
$file->{"PAUSED"} and $file->{"TYPE"} =~ /^</
$file->{"PAUSED"} $file->{"TYPE"} =~ /^</
Truth table66%2/3
A and B
A= $file->{"PAUSED"}B= $file->{"TYPE"} =~ /^</
ABresult
0X0
100
111
3171  
3172 1191 ▶ _debug_desc_fd( "checking for more input", $file ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1191 1191
3173 1191 my $did;
3174 1191 ▶ 1 while $did = $file->_do_filters($self);
Branch: 1 branch
BranchTrueFalseTotal
$did = $file->_do_filters($self) and do { '???' } 61 1191 1252
3175 1191 ▶ if ( defined $file->{FD} && !defined($did) || $did ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file->{'FD'} and not defined $did or $did) { } 0 1191 1191
Condition50%3/6
defined $file->{"FD"} and not defined $did or $did
l!l&&r!l&&!r
001191
defined $file->{"FD"} and not defined $did
!ll&&!rl&&r
4911420
MC/DC0%0/3
defined $file->{"FD"} and not defined $did or $did
defined $file->{"FD"} not defined $did $did
Truth table40%2/5
A and not(B) or C
A= defined $file->{"FD"}B= not defined $didC= $did
ABCresult
11X1
0X11
1011
0X00
1000
3176 0 ▶ _debug_desc_fd( "unpausing", $file ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
3177 0 $file->{PAUSED} = 0;
3178 0 vec( $self->{WIN}, $file->{FD}, 1 ) = 1;
3179  
3180 # vec( $self->{EIN}, $file->{FD}, 1 ) = 1;
3181 0 vec( $self->{PIN}, $file->{FD}, 1 ) = 0;
3182 }
3183 else {
3184 ## This gets incremented occasionally when the IO channel
3185 ## was actually closed. That's a bug, but it seems mostly
3186 ## harmless: it causes us to exit if break_on_io, or to set
3187 ## the timeout to not be forever. I need to fix it, though.
3188 1191 ++$paused;
3189 }
3190 }
3191  
3192 7520 ▶ if (_debugging_details) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging_details()) 0 7520 7520
3193 my $map = join(
3194 '',
3195 map {
3196 0 my $out;
3197 0 ▶ $out = 'r' if vec( $self->{RIN}, $_, 1 );
Branch: 1 branch
BranchTrueFalseTotal
if vec $self->{"RIN"}, $_, 1 0 0 0
3198 0 ▶ $out = $out ? 'b' : 'w' if vec( $self->{WIN}, $_, 1 );
Branch: 2 branches
BranchTrueFalseTotal
if vec $self->{"WIN"}, $_, 1 0 0 0
$out ? : 0 0 0
3199 0 ▶ $out = 'p' if !$out && vec( $self->{PIN}, $_, 1 );
Branch: 1 branch
BranchTrueFalseTotal
if not $out and vec $self->{"PIN"}, $_, 1 0 0 0
Condition0%0/3
not $out and vec $self->{"PIN"}, $_, 1
!ll&&!rl&&r
000
MC/DC0%0/2
not $out and vec $self->{"PIN"}, $_, 1
not $out vec $self->{"PIN"}, $_, 1
Truth table0%0/3
not(A) and B
A= not $outB= vec $self->{"PIN"}, $_, 1
ABresult
0X0
100
111
3200 0 ▶ $out = $out ? uc($out) : 'x' if vec( $self->{EIN}, $_, 1 );
Branch: 2 branches
BranchTrueFalseTotal
if vec $self->{"EIN"}, $_, 1 0 0 0
$out ? : 0 0 0
3201 0 ▶ $out = '-' unless $out;
Branch: 1 branch
BranchTrueFalseTotal
unless $out 0 0 0
3202 0 $out;
3203 } ( 0 .. 1024 )
3204 );
3205 0 $map =~ s/((?:[a-zA-Z-]|\([^\)]*\)){12,}?)-*$/$1/;
3206 0 ▶ _debug 'fds for select: ', $map if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
3207 }
3208  
3209 ## _do_filters may have closed our last fd, and we need to see if
3210 ## we have I/O, or are just waiting for children to exit.
3211 7520 my $p = $self->pumpable;
3212 7520 ▶ last unless $p;
Branch: 1 branch
BranchTrueFalseTotal
unless $p 0 7520 7520
3213 7520 ▶ if ( $p != 0 && ( !defined $timeout || $timeout > 0.1 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p != 0 and !defined($timeout) || $timeout > "0.1") 6813 707 7520
Condition83%5/6
$p != 0 and !defined($timeout) || $timeout > "0.1"
!ll&&!rl&&r
0743882
not defined $timeout or $timeout > "0.1"
l!l&&r!l&&!r
673182707
MC/DC33%1/3
$p != 0 and !defined($timeout) || $timeout > "0.1"
$p != 0 not defined $timeout $timeout > "0.1"
Truth table50%2/4
A and not(B) or C
A= $p != 0B= not defined $timeoutC= $timeout > "0.1"
ABCresult
0XX0
1000
11X1
1011
3214 ## No I/O will wake the select loop up, but we have children
3215 ## lingering, so we need to poll them with a short timeout.
3216 ## Otherwise, assume more input will be coming.
3217  
3218 6813 ▶ if ( !Win32_MODE || $self->{RIN} || $self->{WIN} || $self->{EIN} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not &Win32_MODE() or $self->{'RIN'} or $self->{'WIN'} or $self->{'EIN'}) { } 6813 0 6813
Condition33%3/9
not &Win32_MODE() or $self->{"RIN"} or $self->{"WIN"} or $self->{"EIN"}
l!l&&r!l&&!r
681300
not &Win32_MODE() or $self->{"RIN"} or $self->{"WIN"}
l!l&&r!l&&!r
681300
not &Win32_MODE() or $self->{"RIN"}
l!l&&r!l&&!r
681300
MC/DC0%0/4
not &Win32_MODE() or $self->{"RIN"} or $self->{"WIN"} or $self->{"EIN"}
not &Win32_MODE() $self->{"RIN"} $self->{"WIN"} $self->{"EIN"}
Truth table20%1/5
not(A) or B or C or D
A= not &Win32_MODE()B= $self->{"RIN"}C= $self->{"WIN"}D= $self->{"EIN"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
3219 6813 $timeout = $not_forever;
3220 6813 $not_forever *= 2;
3221 6813 ▶ $not_forever = 0.5 if $not_forever >= 0.5;
Branch: 1 branch
BranchTrueFalseTotal
if $not_forever >= "0.5" 2148 4665 6813
3222 }
3223 else {
3224 # see above rationale for Windows-specific behavior
3225 0 $timeout = $min_select_timeout;
3226 }
3227 }
3228  
3229 ## Make sure we don't block forever in select() because inputs are
3230 ## paused.
3231 7520 ▶ if ( !defined $timeout && !( @{ $self->{PIPES} } - $paused ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $timeout or @{$self->{"PIPES"};} - $paused) 0 7520 7520
Condition33%1/3
defined $timeout or @{$self->{"PIPES"};} - $paused
l!l&&r!l&&!r
752000
MC/DC0%0/2
defined $timeout or @{$self->{"PIPES"};} - $paused
defined $timeout @{$self->{"PIPES"};} - $paused
Truth table33%1/3
A or B
A= defined $timeoutB= @{$self->{"PIPES"};} - $paused
ABresult
1X1
011
000
3232 ## Need to return if we're in pump and all input is paused, or
3233 ## we'll loop until all inputs are unpaused, which is darn near
3234 ## forever. And a day.
3235 0 ▶ if ( $self->{break_on_io} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"break_on_io"}) 0 0 0
3236 0 ▶ _debug "exiting _select(): no I/O to do and timeout=forever"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3237 if _debugging;
3238 0 last;
3239 }
3240  
3241 ## Otherwise, assume more input will be coming.
3242 0 ▶ if ( !Win32_MODE || $self->{RIN} || $self->{WIN} || $self->{EIN} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not &Win32_MODE() or $self->{'RIN'} or $self->{'WIN'} or $self->{'EIN'}) { } 0 0 0
Condition0%0/9
not &Win32_MODE() or $self->{"RIN"} or $self->{"WIN"} or $self->{"EIN"}
l!l&&r!l&&!r
000
not &Win32_MODE() or $self->{"RIN"} or $self->{"WIN"}
l!l&&r!l&&!r
000
not &Win32_MODE() or $self->{"RIN"}
l!l&&r!l&&!r
000
MC/DC0%0/4
not &Win32_MODE() or $self->{"RIN"} or $self->{"WIN"} or $self->{"EIN"}
not &Win32_MODE() $self->{"RIN"} $self->{"WIN"} $self->{"EIN"}
Truth table0%0/5
not(A) or B or C or D
A= not &Win32_MODE()B= $self->{"RIN"}C= $self->{"WIN"}D= $self->{"EIN"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
3243 0 $timeout = $not_forever;
3244 0 $not_forever *= 2;
3245 0 ▶ $not_forever = 0.5 if $not_forever >= 0.5;
Branch: 1 branch
BranchTrueFalseTotal
if $not_forever >= "0.5" 0 0 0
3246 }
3247 else {
3248 0 $timeout = $min_select_timeout;
3249 }
3250 }
3251  
3252 7520 ▶ _debug 'timeout=', defined $timeout ? $timeout : 'forever'
Branch: 2 branches
BranchTrueFalseTotal
if &_debugging_details() 0 7520 7520
defined $timeout ? : 0 0 0
3253 if _debugging_details;
3254  
3255 7520 my $nfound;
3256 7520 ▶ unless (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 7520 7520
3257 $nfound = select(
3258 $self->{ROUT} = $self->{RIN},
3259 $self->{WOUT} = $self->{WIN},
3260 $self->{EOUT} = $self->{EIN},
3261 7520 $timeout
3262 );
3263 }
3264 else {
3265 0 my @in = map $self->{$_}, qw( RIN WIN EIN );
3266 ## Win32's select() on Win32 seems to die if passed vectors of
3267 ## all 0's. Need to report this when I get back online.
3268 0 for (@in) {
3269 0 ▶ $_ = undef unless index( ( unpack "b*", $_ ), 1 ) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
unless index(unpack("b*", $_), 1) != -1 0 0 0
3270 }
3271  
3272 $nfound = select(
3273 $self->{ROUT} = $in[0],
3274 $self->{WOUT} = $in[1],
3275 0 $self->{EOUT} = $in[2],
3276 $timeout
3277 );
3278  
3279 0 for ( $self->{ROUT}, $self->{WOUT}, $self->{EOUT} ) {
3280 0 ▶ $_ = "" unless defined $_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 0 0 0
3281 }
3282 }
3283 7520 ▶ last if !$nfound && $self->{non_blocking};
Branch: 1 branch
BranchTrueFalseTotal
if not $nfound and $self->{"non_blocking"} 700 6820 7520
Condition100%3/3
not $nfound and $self->{"non_blocking"}
!ll&&!rl&&r
30303790700
MC/DC100%2/2
not $nfound and $self->{"non_blocking"}
not $nfound $self->{"non_blocking"}
Truth table100%3/3
not(A) and B
A= not $nfoundB= $self->{"non_blocking"}
ABresult
0X0
100
111
3284  
3285 6820 ▶ if ( $nfound < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nfound < 0) 69 6751 6820
3286 69 ▶ if ( $!{EINTR} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($!{'EINTR'}) { } 69 0 69
3287  
3288 # Caught a signal before any FD went ready. Ensure that
3289 # the bit fields reflect "no FDs ready".
3290 69 $self->{ROUT} = $self->{WOUT} = $self->{EOUT} = '';
3291 69 $nfound = 0;
3292 }
3293 else {
3294 0 croak "$! in select";
3295 }
3296 }
3297 ## TODO: Analyze the EINTR failure mode and see if this patch
3298 ## is adequate and optimal.
3299 ## TODO: Add an EINTR test to the test suite.
3300  
3301 6820 ▶ if (_debugging_details) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging_details()) 0 6820 6820
3302 my $map = join(
3303 '',
3304 map {
3305 0 my $out;
3306 0 ▶ $out = 'r' if vec( $self->{ROUT}, $_, 1 );
Branch: 1 branch
BranchTrueFalseTotal
if vec $self->{"ROUT"}, $_, 1 0 0 0
3307 0 ▶ $out = $out ? 'b' : 'w' if vec( $self->{WOUT}, $_, 1 );
Branch: 2 branches
BranchTrueFalseTotal
if vec $self->{"WOUT"}, $_, 1 0 0 0
$out ? : 0 0 0
3308 0 ▶ $out = $out ? uc($out) : 'x' if vec( $self->{EOUT}, $_, 1 );
Branch: 2 branches
BranchTrueFalseTotal
if vec $self->{"EOUT"}, $_, 1 0 0 0
$out ? : 0 0 0
3309 0 ▶ $out = '-' unless $out;
Branch: 1 branch
BranchTrueFalseTotal
unless $out 0 0 0
3310 0 $out;
3311 } ( 0 .. 128 )
3312 );
3313 0 $map =~ s/((?:[a-zA-Z-]|\([^\)]*\)){12,}?)-*$/$1/;
3314 0 _debug "selected ", $map;
3315 }
3316  
3317 ## Need to copy since _clobber alters @{$self->{PIPES}}.
3318 ## TODO: Rethink _clobber(). Rethink $file->{PAUSED}, too.
3319 6820 my @pipes = @{ $self->{PIPES} };
3320 6820 ▶ $io_occurred = $_->poll($self) ? 1 : $io_occurred for @pipes;
Branch: 1 branch
BranchTrueFalseTotal
$_->poll($self) ? : 1693 9374 11067
3321  
3322 # FILE:
3323 # for my $pipe ( @pipes ) {
3324 # ## Pipes can be shared among kids. If another kid closes the
3325 # ## pipe, then its {FD} will be undef. Also, on Win32, pipes can
3326 # ## be optimized to be files, in which case the FD is left undef
3327 # ## so we don't try to select() on it.
3328 # if ( $pipe->{TYPE} =~ /^>/
3329 # && defined $pipe->{FD}
3330 # && vec( $self->{ROUT}, $pipe->{FD}, 1 )
3331 # ) {
3332 # _debug_desc_fd( "filtering data from", $pipe ) if _debugging_details;
3333 #confess "phooey" unless UNIVERSAL::isa( $pipe, "IPC::Run::IO" );
3334 # $io_occurred = 1 if $pipe->_do_filters( $self );
3335 #
3336 # next FILE unless defined $pipe->{FD};
3337 # }
3338 #
3339 # ## On Win32, pipes to the child can be optimized to be files
3340 # ## and FD left undefined so we won't select on it.
3341 # if ( $pipe->{TYPE} =~ /^</
3342 # && defined $pipe->{FD}
3343 # && vec( $self->{WOUT}, $pipe->{FD}, 1 )
3344 # ) {
3345 # _debug_desc_fd( "filtering data to", $pipe ) if _debugging_details;
3346 # $io_occurred = 1 if $pipe->_do_filters( $self );
3347 #
3348 # next FILE unless defined $pipe->{FD};
3349 # }
3350 #
3351 # if ( defined $pipe->{FD} && vec( $self->{EOUT}, $pipe->{FD}, 1 ) ) {
3352 # ## BSD seems to sometimes raise the exceptional condition flag
3353 # ## when a pipe is closed before we read it's last data. This
3354 # ## causes spurious warnings and generally renders the exception
3355 # ## mechanism useless for our purposes. The exception
3356 # ## flag semantics are too variable (they're device driver
3357 # ## specific) for me to easily map to any automatic action like
3358 # ## warning or croaking (try running v0.42 if you don't believe me
3359 # ## :-).
3360 # warn "Exception on descriptor $pipe->{FD}";
3361 # }
3362 # }
3363 }
3364  
3365 1821 return;
3366 }
3367  
3368 sub _cleanup {
3369 1376 ▶ my IPC::Run $self = shift;
Subroutine _cleanup: called CC=23 SCAR=32.4
3370 1376 ▶ _debug "cleaning up" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1376 1376
3371  
3372 1376 for ( values %{ $self->{PTYS} } ) {
3373 10 ▶ next unless ref $_;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $_ 6 4 10
3374 4 eval {
3375 4 ▶ _debug "closing slave fd ", fileno $_->slave if _debugging_data;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 4 4
3376 4 close $_->slave;
3377 };
3378 4 ▶ carp $@ . " while closing ptys" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
3379 4 eval {
3380 4 ▶ _debug "closing master fd ", fileno $_ if _debugging_data;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 4 4
3381 4 close $_;
3382 };
3383 4 ▶ carp $@ . " closing ptys" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
3384 }
3385  
3386 1376 ▶ _debug "cleaning up pipes" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1376 1376
3387 ## _clobber modifies PIPES
3388 1376 ▶ $self->_clobber( $self->{PIPES}->[0] ) while @{ $self->{PIPES} };
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{"PIPES"};} and do { $self->_clobber($self->{"PIPES"}[0]) } 38 1376 1414
3389  
3390 # reap kids
3391 1376 for my $kid ( @{ $self->{KIDS} } ) {
3392 1393 ▶ if ( !length $kid->{PID} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not length $kid->{'PID'}) { } 56 1337 1393
3393 56 ▶ _debug 'never ran child ', $kid->{NUM}, ", can't reap"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 56 56
3394 if _debugging;
3395 56 for my $op ( @{ $kid->{OPS} } ) {
3396 _close( $op->{TFD} )
3397 82 ▶ if defined $op->{TFD} && !defined $op->{TEMP_FILE_HANDLE};
Branch: 1 branch
BranchTrueFalseTotal
if defined $op->{"TFD"} and not defined $op->{"TEMP_FILE_HANDLE"} 0 82 82
Condition33%1/3
defined $op->{"TFD"} and not defined $op->{"TEMP_FILE_HANDLE"}
!ll&&!rl&&r
8200
MC/DC0%0/2
defined $op->{"TFD"} and not defined $op->{"TEMP_FILE_HANDLE"}
defined $op->{"TFD"} not defined $op->{"TEMP_FILE_HANDLE"}
Truth table33%1/3
A and not(B)
A= defined $op->{"TFD"}B= not defined $op->{"TEMP_FILE_HANDLE"}
ABresult
0X0
100
111
3398 }
3399 }
3400 else {
3401 1337 _waitpid( $kid, 0 );
3402 }
3403 }
3404  
3405 # OPS cleanup. Kids may share an OPS object; search for "also to write".
3406 # Example harness: run(['echo',1], '&', ['echo',2], '>', \$out). Hence,
3407 # this starts after the last reap.
3408 1376 for my $kid ( @{ $self->{KIDS} } ) {
3409  
3410 # if ( defined $kid->{DEBUG_FD} ) {
3411 # die;
3412 # @{$kid->{OPS}} = grep
3413 # ! defined $_->{KFD} || $_->{KFD} != $kid->{DEBUG_FD},
3414 # @{$kid->{OPS}};
3415 # $kid->{DEBUG_FD} = undef;
3416 # }
3417  
3418 1393 ▶ _debug "cleaning up filters at kid ", $kid->{NUM} if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1393 1393
3419 1393 for my $op ( @{ $kid->{OPS} } ) {
3420 2481 @{ $op->{FILTERS} } = grep {
3421 2544 my $filter = $_;
3422 2544 !grep $filter == $_, @{ $self->{TEMP_FILTERS} };
3423 2481 } @{ $op->{FILTERS} };
3424 }
3425  
3426 1393 for my $op ( @{ $kid->{OPS} } ) {
3427 2481 ▶ $op->_cleanup($self) if UNIVERSAL::isa( $op, "IPC::Run::IO" );
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($op, "IPC::Run::IO") 2309 172 2481
3428 }
3429 }
3430 1376 $self->{STATE} = _finished;
3431 1376 @{ $self->{TEMP_FILTERS} } = ();
3432 1376 ▶ _debug "done cleaning up" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1376 1376
3433  
3434 1376 ▶ POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"DEBUG_FD"} 0 1376 1376
3435 1376 $self->{DEBUG_FD} = undef;
3436 }
3437  
3438 =pod
3439  
3440 =item pump
3441  
3442 pump $h;
3443 $h->pump;
3444  
3445 Pump accepts a single parameter harness. It blocks until it delivers some
3446 input or receives some output. It returns TRUE if there is still input or
3447 output to be done, FALSE otherwise.
3448  
3449 pump() will automatically call start() if need be, so you may call harness()
3450 then proceed to pump() if that helps you structure your application.
3451  
3452 If pump() is called after all harnessed activities have completed, a "process
3453 ended prematurely" exception to be thrown. This allows for simple scripting
3454 of external applications without having to add lots of error handling code at
3455 each step of the script:
3456  
3457 $h = harness \@smbclient, \$in, \$out, $err;
3458  
3459 $in = "cd /foo\n";
3460 $h->pump until $out =~ /^smb.*> \Z/m;
3461 die "error cding to /foo:\n$out" if $out =~ "ERR";
3462 $out = '';
3463  
3464 $in = "mget *\n";
3465 $h->pump until $out =~ /^smb.*> \Z/m;
3466 die "error retrieving files:\n$out" if $out =~ "ERR";
3467  
3468 $h->finish;
3469  
3470 warn $err if $err;
3471  
3472 =cut
3473  
3474 sub pump {
3475 919 ▶ die "pump() takes only a single harness as a parameter"
Subroutine pump: called CC=6 SCAR=19.2
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__) 0 919 919
Condition33%1/3
@_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__)
!ll&&!rl&&r
00919
MC/DC0%0/2
@_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__)
@_ == 1 UNIVERSAL::isa($_[0], __PACKAGE__)
Truth table33%1/3
A and B
A= @_ == 1B= UNIVERSAL::isa($_[0], __PACKAGE__)
ABresult
0X0
100
111
3476 unless @_ == 1 && UNIVERSAL::isa( $_[0], __PACKAGE__ );
3477  
3478 919 my IPC::Run $self = shift;
3479  
3480 919 local $cur_self = $self;
3481  
3482 919 ▶ _debug "** pumping"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 919 919
3483 if _debugging;
3484  
3485 # my $r = eval {
3486 919 ▶ $self->start if $self->{STATE} < _started;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"STATE"} < 3 0 919 919
3487 919 ▶ croak "process ended prematurely" unless $self->pumpable;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->pumpable 0 919 919
3488  
3489 919 $self->{auto_close_ins} = 0;
3490 919 $self->{break_on_io} = 1;
3491 919 $self->_select_loop;
3492 910 return $self->pumpable;
3493  
3494 # };
3495 # if ( $@ ) {
3496 # my $x = $@;
3497 # _debug $x if _debugging && $x;
3498 # eval { $self->_cleanup };
3499 # warn $@ if $@;
3500 # die $x;
3501 # }
3502 # return $r;
3503 }
3504  
3505 =pod
3506  
3507 =item pump_nb
3508  
3509 pump_nb $h;
3510 $h->pump_nb;
3511  
3512 "pump() non-blocking", pumps if anything's ready to be pumped, returns
3513 immediately otherwise. This is useful if you're doing some long-running
3514 task in the foreground, but don't want to starve any child processes.
3515  
3516 =cut
3517  
3518 sub pump_nb {
3519 700 ▶ my IPC::Run $self = shift;
Subroutine pump_nb: called CC=2 SCAR=7.0
Pod documented
3520  
3521 700 $self->{non_blocking} = 1;
3522 700 my $r = eval { $self->pump };
3523 700 $self->{non_blocking} = 0;
3524 700 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 700 700
3525 700 return $r;
3526 }
3527  
3528 =pod
3529  
3530 =item pumpable
3531  
3532 Returns TRUE if calling pump() won't throw an immediate "process ended
3533 prematurely" exception. This means that there are open I/O channels or
3534 active processes. May yield the parent processes' time slice for 0.01
3535 second if all pipes are to the child and all are paused. In this case
3536 we can't tell if the child is dead, so we yield the processor and
3537 then attempt to reap the child in a nonblocking way.
3538  
3539 =cut
3540  
3541 ## Undocumented feature (don't depend on it outside this module):
3542 ## returns -1 if we have I/O channels open, or >0 if no I/O channels
3543 ## open, but we have kids running. This allows the select loop
3544 ## to poll for child exit.
3545 sub pumpable {
3546 19869 ▶ my IPC::Run $self = shift;
Subroutine pumpable: called CC=4 SCAR=13.9
Pod documented
3547  
3548 ## There's a catch-22 we can get in to if there is only one pipe left
3549 ## open to the child and it's paused (ie the SCALAR it's tied to
3550 ## is ''). It's paused, so we're not select()ing on it, so we don't
3551 ## check it to see if the child attached to it is alive and it stays
3552 ## in @{$self->{PIPES}} forever. So, if all pipes are paused, see if
3553 ## we can reap the child.
3554 19869 ▶ return -1 if grep !$_->{PAUSED}, @{ $self->{PIPES} };
Branch: 1 branch
BranchTrueFalseTotal
if grep((!$_->{"PAUSED"}), @{$$self{"PIPES"};}) 17415 2454 19869
3555  
3556 ## See if the child is dead.
3557 2454 $self->reap_nb;
3558 2454 ▶ return 0 unless $self->_running_kids;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_running_kids 1797 657 2454
3559  
3560 ## If we reap_nb and it's not dead yet, yield to it to see if it
3561 ## exits.
3562 ##
3563 ## A better solution would be to unpause all the pipes, but I tried that
3564 ## and it never errored on linux. Sigh.
3565 657 select undef, undef, undef, 0.0001;
3566  
3567 ## try again
3568 657 $self->reap_nb;
3569 657 ▶ return 0 unless $self->_running_kids;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_running_kids 44 613 657
3570  
3571 613 return -1; ## There are pipes waiting
3572 }
3573  
3574 sub _running_kids {
3575 3128 ▶ my IPC::Run $self = shift;
Subroutine _running_kids: called CC=2 SCAR=7.0
3576 return grep
3577 defined $_->{PID} && !defined $_->{RESULT},
3578 3128 ▶ @{ $self->{KIDS} };
Condition66%2/3
defined $_->{'PID'} && !defined($_->{'RESULT'})
!ll&&!rl&&r
018781278
MC/DC50%1/2
defined $_->{'PID'} && !defined($_->{'RESULT'})
defined $_->{'PID'} !defined($_->{'RESULT'})
Truth table66%2/3
A && not(B)
A= defined $_->{'PID'}B= !defined($_->{'RESULT'})
ABresult
0X0
100
111
3579 }
3580  
3581 =pod
3582  
3583 =item reap_nb
3584  
3585 Attempts to reap child processes, but does not block.
3586  
3587 Does not currently take any parameters, one day it will allow specific
3588 children to be reaped.
3589  
3590 Only call this from a signal handler if your C<perl> is recent enough
3591 to have safe signal handling (5.6.1 did not, IIRC, but it was being discussed
3592 on perl5-porters). Calling this (or doing any significant work) in a signal
3593 handler on older C<perl>s is asking for seg faults.
3594  
3595 =cut
3596  
3597 127 my $still_runnings;
3598  
3599 sub reap_nb {
3600 3128 ▶ my IPC::Run $self = shift;
Subroutine reap_nb: called CC=2 SCAR=6.9
Pod documented
3601  
3602 3128 local $cur_self = $self;
3603  
3604 ## No more pipes, look to see if all the kids yet live, reaping those
3605 ## that haven't. I'd use $SIG{CHLD}/$SIG{CLD}, but that's broken
3606 ## on older (SYSV) platforms and perhaps less portable than waitpid().
3607 ## This could be slow with a lot of kids, but that's rare and, well,
3608 ## a lot of kids is slow in the first place.
3609 ## Oh, and this keeps us from reaping other children the process
3610 ## may have spawned.
3611 3128 for my $kid ( @{ $self->{KIDS} } ) {
3612 3156 _waitpid( $kid, 1 );
3613 }
3614 }
3615  
3616 # Support routine (non-method) for waitpid() or platform's equivalent. Sets $?
3617 # and $_[0]->{RESULT} iff the kid exited.
3618 sub _waitpid {
3619 4493 ▶ my ( $kid, $nohang ) = @_;
Subroutine _waitpid: called CC=23 SCAR=51.3
3620  
3621 4493 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 4493 4493
3622 0 require Win32::Process;
3623  
3624 0 ▶ return if !defined $kid->{PROCESS} || defined $kid->{RESULT};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $kid->{"PROCESS"} or defined $kid->{"RESULT"} 0 0 0
Condition0%0/3
not defined $kid->{"PROCESS"} or defined $kid->{"RESULT"}
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $kid->{"PROCESS"} or defined $kid->{"RESULT"}
not defined $kid->{"PROCESS"} defined $kid->{"RESULT"}
Truth table0%0/3
not(A) or B
A= not defined $kid->{"PROCESS"}B= defined $kid->{"RESULT"}
ABresult
1X1
011
000
3625 0 ▶ my $wait_timeout = $nohang ? 0 : Win32::Process::INFINITE();
Branch: 1 branch
BranchTrueFalseTotal
$nohang ? : 0 0 0
3626 0 ▶ unless ( $kid->{PROCESS}->Wait($wait_timeout) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($kid->{"PROCESS"}->Wait($wait_timeout)) 0 0 0
3627 0 ▶ confess "kid $kid->{PID} still running after indefinite wait"
Branch: 1 branch
BranchTrueFalseTotal
unless $nohang 0 0 0
3628 unless $nohang;
3629 0 ▶ _debug "kid $kid->{NUM} ($kid->{PID}) still running"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
3630 if _debugging_details;
3631 0 return;
3632 }
3633  
3634 0 ▶ _debug "kid $kid->{NUM} ($kid->{PID}) exited"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3635 if _debugging;
3636  
3637 0 my $native_result;
3638 0 ▶ $kid->{PROCESS}->GetExitCode($native_result)
Branch: 1 branch
BranchTrueFalseTotal
$kid->{"PROCESS"}->GetExitCode($native_result) or croak("$! while GetExitCode()ing for Win32 process") 0 0 0
3639 or croak "$! while GetExitCode()ing for Win32 process";
3640  
3641 0 ▶ unless ( defined $native_result ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $native_result) { } 0 0 0
3642 0 $kid->{RESULT} = "0 but true";
3643 0 $? = $kid->{RESULT} = 0x0F;
3644 }
3645 else {
3646 0 my $win32_full_result = $native_result << 8;
3647 0 ▶ if ( $win32_full_result >> 8 != $native_result ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($win32_full_result >> 8 != $native_result) 0 0 0
3648  
3649 # !USE_64_BIT_INT build and exit code > 0xFFFFFF
3650 0 require Math::BigInt;
3651 0 $win32_full_result = Math::BigInt->new($native_result);
3652 0 $win32_full_result->blsft(8);
3653 }
3654 0 $? = $kid->{RESULT} = $win32_full_result;
3655 }
3656 }
3657 else {
3658 4493 ▶ return if !defined $kid->{PID} || defined $kid->{RESULT};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $kid->{"PID"} or defined $kid->{"RESULT"} 1882 2611 4493
Condition66%2/3
not defined $kid->{"PID"} or defined $kid->{"RESULT"}
l!l&&r!l&&!r
018822611
MC/DC50%1/2
not defined $kid->{"PID"} or defined $kid->{"RESULT"}
not defined $kid->{"PID"} defined $kid->{"RESULT"}
Truth table66%2/3
not(A) or B
A= not defined $kid->{"PID"}B= defined $kid->{"RESULT"}
ABresult
1X1
011
000
3659 2611 ▶ my $pid = waitpid $kid->{PID}, $nohang ? POSIX::WNOHANG() : 0;
Branch: 1 branch
BranchTrueFalseTotal
$nohang ? : 2212 399 2611
3660 2611 ▶ unless ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 1278 1333 2611
3661 1278 ▶ confess "kid $kid->{PID} still running after indefinite wait"
Branch: 1 branch
BranchTrueFalseTotal
unless $nohang 0 1278 1278
3662 unless $nohang;
3663 1278 ▶ _debug "$kid->{NUM} ($kid->{PID}) still running"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1278 1278
3664 if _debugging_details;
3665 1278 return;
3666 }
3667  
3668 1333 ▶ if ( $pid < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid < 0) { } 0 1333 1333
3669 0 ▶ _debug "No such process: $kid->{PID}\n" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3670 0 $kid->{RESULT} = "unknown result, unknown PID";
3671 }
3672 else {
3673 1333 ▶ _debug "kid $kid->{NUM} ($kid->{PID}) exited"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 1333 1333
3674 if _debugging;
3675  
3676 confess "waitpid returned the wrong PID: $pid instead of $kid->{PID}"
3677 1333 ▶ unless $pid == $kid->{PID};
Branch: 1 branch
BranchTrueFalseTotal
unless $pid == $kid->{"PID"} 0 1333 1333
3678 1333 ▶ _debug "$kid->{PID} returned $?\n" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 1333 1333
3679 1333 $kid->{RESULT} = $?;
3680 }
3681 }
3682 }
3683  
3684 =pod
3685  
3686 =item finish
3687  
3688 This must be called after the last start() or pump() call for a harness,
3689 or your system will accumulate defunct processes and you may "leak"
3690 file descriptors.
3691  
3692 finish() returns TRUE if all children returned 0 (and were not signaled and did
3693 not coredump, ie ! $?), and FALSE otherwise (this is like run(), and the
3694 opposite of system()).
3695  
3696 Once a harness has been finished, it may be run() or start()ed again,
3697 including by pump()s auto-start.
3698  
3699 If this throws an exception rather than a normal exit, the harness may
3700 be left in an unstable state, it's best to kill the harness to get rid
3701 of all the child processes, etc.
3702  
3703 Specifically, if a timeout expires in finish(), finish() will not
3704 kill all the children. Call C<< $h->kill_kill >> in this case if you care.
3705 This differs from the behavior of L</run>.
3706  
3707 =cut
3708  
3709 sub finish {
3710 1310 ▶ my IPC::Run $self = shift;
Subroutine finish: called CC=8 SCAR=20.9
Pod documented
3711 1310 ▶ my $options = @_ && ref $_[-1] eq 'HASH' ? pop : {};
Branch: 1 branch
BranchTrueFalseTotal
@_ && ref $_[-1] eq 'HASH' ? : 0 1310 1310
Condition33%1/3
@_ and ref $_[-1] eq "HASH"
!ll&&!rl&&r
131000
MC/DC0%0/2
@_ and ref $_[-1] eq "HASH"
@_ ref $_[-1] eq "HASH"
Truth table33%1/3
A and B
A= @_B= ref $_[-1] eq "HASH"
ABresult
0X0
100
111
3712  
3713 1310 local $cur_self = $self;
3714  
3715 1310 ▶ _debug "** finishing" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 1310 1310
3716  
3717 1310 $self->{non_blocking} = 0;
3718 1310 $self->{auto_close_ins} = 1;
3719 1310 $self->{break_on_io} = 0;
3720  
3721 # We don't alter $self->{clear_ins}, start() and run() control it.
3722  
3723 1310 ▶ if ( %{ $self->{PTYS} } || @{ $self->{PIPES} } || @{ $self->{TIMERS} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$self->{"PTYS"};} or @{$self->{"PIPES"};} or @{$self->{"TIMERS"};}) 902 398 1300
Condition100%6/6
%{$self->{"PTYS"};} or @{$self->{"PIPES"};} or @{$self->{"TIMERS"};}
l!l&&r!l&&!r
9102398
%{$self->{"PTYS"};} or @{$self->{"PIPES"};}
l!l&&r!l&&!r
10900400
MC/DC100%3/3
%{$self->{"PTYS"};} or @{$self->{"PIPES"};} or @{$self->{"TIMERS"};}
%{$self->{"PTYS"};} @{$self->{"PIPES"};} @{$self->{"TIMERS"};}
Truth table100%4/4
A or B or C
A= %{$self->{"PTYS"};}B= @{$self->{"PIPES"};}C= @{$self->{"TIMERS"};}
ABCresult
1XX1
01X1
0011
0000
3724 912 ▶ while ( $self->pumpable ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->pumpable) 912 911 1823
3725 912 $self->_select_loop($options);
3726 }
3727 }
3728 1309 $self->_cleanup;
3729  
3730 1309 return !$self->full_result;
3731 }
3732  
3733 =pod
3734  
3735 =item result
3736  
3737 $h->result;
3738  
3739 Returns the first non-zero result code (ie $? >> 8). See L</full_result> to
3740 get the $? value for a child process.
3741  
3742 To get the result of a particular child, do:
3743  
3744 $h->result( 0 ); # first child's $? >> 8
3745 $h->result( 1 ); # second child
3746  
3747 or
3748  
3749 ($h->results)[0]
3750 ($h->results)[1]
3751  
3752 Returns undef if no child processes were spawned and no child number was
3753 specified. Throws an exception if an out-of-range child number is passed.
3754  
3755 =cut
3756  
3757 sub _assert_finished {
3758 1321 ▶ my IPC::Run $self = $_[0];
Subroutine _assert_finished: called CC=3 SCAR=11.7
3759  
3760 1321 ▶ croak "Harness not run" unless $self->{STATE} >= _finished;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} >= 2 0 1321 1321
3761 1321 ▶ croak "Harness not finished running" unless $self->{STATE} == _finished;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} == 2 0 1321 1321
3762 }
3763  
3764 sub _child_result {
3765 8 ▶ my IPC::Run $self = shift;
Subroutine _child_result: called CC=3 SCAR=12.3
3766  
3767 8 my ($which) = @_;
3768 croak(
3769 "Only ",
3770 0 scalar( @{ $self->{KIDS} } ),
3771 " child processes, no process $which"
3772 8 ▶ ) unless $which >= 0 && $which <= $#{ $self->{KIDS} };
Branch: 1 branch
BranchTrueFalseTotal
unless $which >= 0 and $which <= $#{$$self{"KIDS"};} 0 8 8
Condition33%1/3
$which >= 0 and $which <= $#{$$self{"KIDS"};}
!ll&&!rl&&r
008
MC/DC0%0/2
$which >= 0 and $which <= $#{$$self{"KIDS"};}
$which >= 0 $which <= $#{$$self{"KIDS"};}
Truth table33%1/3
A and B
A= $which >= 0B= $which <= $#{$$self{"KIDS"};}
ABresult
0X0
100
111
3773 8 return $self->{KIDS}->[$which]->{RESULT};
3774 }
3775  
3776 sub result {
3777 5 ▶ &_assert_finished;
Subroutine result: called CC=5 SCAR=16.1
Pod documented
3778 5 my IPC::Run $self = shift;
3779  
3780 5 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 4 1 5
3781 4 my ($which) = @_;
3782 4 return $self->_child_result($which) >> 8;
3783 }
3784 else {
3785 1 ▶ return undef unless @{ $self->{KIDS} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"KIDS"};} 0 1 1
3786 1 for ( @{ $self->{KIDS} } ) {
3787 4 ▶ return $_->{RESULT} >> 8 if $_->{RESULT} >> 8;
Branch: 1 branch
BranchTrueFalseTotal
if $_->{"RESULT"} >> 8 1 3 4
3788 }
3789 }
3790 }
3791  
3792 =pod
3793  
3794 =item results
3795  
3796 Returns a list of child exit values. See L</full_results> if you want to
3797 know if a signal killed the child.
3798  
3799 Throws an exception if the harness is not in a finished state.
3800
3801 =cut
3802  
3803 sub results {
3804 1 ▶ &_assert_finished;
Subroutine results: called CC=1 SCAR=0.0
Pod documented
3805 1 my IPC::Run $self = shift;
3806  
3807 # we add 0 here to stop warnings associated with "unknown result, unknown PID"
3808 1 return map { ( 0 + $_->{RESULT} ) >> 8 } @{ $self->{KIDS} };
3809 }
3810  
3811 =pod
3812  
3813 =item full_result
3814  
3815 $h->full_result;
3816  
3817 Returns the first non-zero $?. See L</result> to get the first $? >> 8
3818 value for a child process.
3819  
3820 To get the result of a particular child, do:
3821  
3822 $h->full_result( 0 ); # first child's $?
3823 $h->full_result( 1 ); # second child
3824  
3825 or
3826  
3827 ($h->full_results)[0]
3828 ($h->full_results)[1]
3829  
3830 Returns undef if no child processes were spawned and no child number was
3831 specified. Throws an exception if an out-of-range child number is passed.
3832  
3833 =cut
3834  
3835 sub full_result {
3836 1314 ▶ &_assert_finished;
Subroutine full_result: called CC=5 SCAR=16.1
Pod documented
3837  
3838 1314 my IPC::Run $self = shift;
3839  
3840 1314 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 4 1310 1314
3841 4 my ($which) = @_;
3842 4 return $self->_child_result($which);
3843 }
3844 else {
3845 1310 ▶ return undef unless @{ $self->{KIDS} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"KIDS"};} 2 1308 1310
3846 1308 for ( @{ $self->{KIDS} } ) {
3847 1328 ▶ return $_->{RESULT} if $_->{RESULT};
Branch: 1 branch
BranchTrueFalseTotal
if $_->{"RESULT"} 199 1129 1328
3848 }
3849 }
3850 }
3851  
3852 =pod
3853  
3854 =item full_results
3855  
3856 Returns a list of child exit values as returned by C<wait>. See L</results>
3857 if you don't care about coredumps or signals.
3858  
3859 Throws an exception if the harness is not in a finished state.
3860
3861 =cut
3862  
3863 sub full_results {
3864 1 ▶ &_assert_finished;
Subroutine full_results: called CC=3 SCAR=11.2
Pod documented
3865 1 my IPC::Run $self = shift;
3866  
3867 1 ▶ croak "Harness not run" unless $self->{STATE} >= _finished;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} >= 2 0 1 1
3868 1 ▶ croak "Harness not finished running" unless $self->{STATE} == _finished;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} == 2 0 1 1
3869  
3870 1 return map $_->{RESULT}, @{ $self->{KIDS} };
3871 }
3872  
3873 ##
3874 ## Filter Scaffolding
3875 ##
3876 use vars (
3877 127 '$filter_op', ## The op running a filter chain right now
3878 '$filter_num', ## Which filter is being run right now.
3879 127 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
3880  
3881 ##
3882 ## A few filters and filter constructors
3883 ##
3884  
3885 =pod
3886  
3887 =back
3888  
3889 =back
3890  
3891 =head1 FILTERS
3892  
3893 These filters are used to modify input our output between a child
3894 process and a scalar or subroutine endpoint.
3895  
3896 =over
3897  
3898 =item binary
3899  
3900 run \@cmd, ">", binary, \$out;
3901 run \@cmd, ">", binary, \$out; ## Any TRUE value to enable
3902 run \@cmd, ">", binary 0, \$out; ## Any FALSE value to disable
3903  
3904 This is a constructor for a "binmode" "filter" that tells IPC::Run to keep
3905 the carriage returns that would ordinarily be edited out for you (binmode
3906 is usually off). This is not a real filter, but an option masquerading as
3907 a filter.
3908  
3909 It's not named "binmode" because you're likely to want to call Perl's binmode
3910 in programs that are piping binary data around.
3911  
3912 =cut
3913  
3914 sub binary(;$) {
3915 91 ▶ my $enable = @_ ? shift : 1;
Subroutine binary: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 26 65 91
3916 91 ▶ return bless sub { $enable }, "IPC::Run::binmode_pseudo_filter";
Subroutine __ANON__: called CC=1 SCAR=0.0
3917 }
3918  
3919 =pod
3920  
3921 =item new_chunker
3922  
3923 This breaks a stream of data in to chunks, based on an optional
3924 scalar or regular expression parameter. The default is the Perl
3925 input record separator in $/, which is a newline be default.
3926  
3927 run \@cmd, '>', new_chunker, \&lines_handler;
3928 run \@cmd, '>', new_chunker( "\r\n" ), \&lines_handler;
3929  
3930 Because this uses $/ by default, you should always pass in a parameter
3931 if you are worried about other code (modules, etc) modifying $/.
3932  
3933 If this filter is last in a filter chain that dumps in to a scalar,
3934 the scalar must be set to '' before a new chunk will be written to it.
3935  
3936 As an example of how a filter like this can be written, here's a
3937 chunker that splits on newlines:
3938  
3939 sub line_splitter {
3940 my ( $in_ref, $out_ref ) = @_;
3941  
3942 return 0 if length $$out_ref;
3943  
3944 return input_avail && do {
3945 while (1) {
3946 if ( $$in_ref =~ s/\A(.*?\n)// ) {
3947 $$out_ref .= $1;
3948 return 1;
3949 }
3950 my $hmm = get_more_input;
3951 unless ( defined $hmm ) {
3952 $$out_ref = $$in_ref;
3953 $$in_ref = '';
3954 return length $$out_ref ? 1 : 0;
3955 }
3956 return 0 if $hmm eq 0;
3957 }
3958 }
3959 };
3960  
3961 =cut
3962  
3963 sub new_chunker(;$) {
3964 5 ▶ my ($re) = @_;
Subroutine new_chunker: called CC=3 SCAR=11.0
Pod documented
3965 5 ▶ $re = $/ if _empty $re;
Branch: 1 branch
BranchTrueFalseTotal
if &_empty($re) 3 2 5
3966 5 ▶ $re = quotemeta($re) unless ref $re eq 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $re eq "Regexp" 4 1 5
3967 5 $re = qr/\A(.*?$re)/s;
3968  
3969 return sub {
3970 56 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=7 SCAR=19.7
3971  
3972 56 ▶ return 0 if length $$out_ref;
Branch: 1 branch
BranchTrueFalseTotal
if length $$out_ref 0 56 56
3973  
3974 56 ▶ return input_avail && do {
Condition66%2/3
&input_avail() && do { while (1) { if ($$in_ref =~ s/$re//) { $$out_ref .= $1; return 1; } ; my $hmm = &get_more_input(); unless (defined $hmm) { $$out_ref = $$in_ref; $$in_ref = ''; return length $$out_ref ? 1 : 0; } ; return 0 if $hmm eq 0; } }
!ll&&!rl&&r
35210
MC/DC0%0/2
&input_avail() && do { while (1) { if ($$in_ref =~ s/$re//) { $$out_ref .= $1; return 1; } ; my $hmm = &get_more_input(); unless (defined $hmm) { $$out_ref = $$in_ref; $$in_ref = ''; return length $$out_ref ? 1 : 0; } ; return 0 if $hmm eq 0; } }
&input_avail() do { while (1) { if ($$in_ref =~ s/$re//) { $$out_ref .= $1; return 1; } ; my $hmm = &get_more_input(); unless (defined $hmm) { $$out_ref = $$in_ref; $$in_ref = ''; return length $$out_ref ? 1 : 0; } ; return 0 if $hmm eq 0; } }
Truth table33%1/3
A && B
A= &input_avail()B= do { while (1) { if ($$in_ref =~ s/$re//) { $$out_ref .= $1; return 1; } ; my $hmm = &get_more_input(); unless (defined $hmm) { $$out_ref = $$in_ref; $$in_ref = ''; return length $$out_ref ? 1 : 0; } ; return 0 if $hmm eq 0; } }
ABresult
0X0
100
111
3975 21 while (1) {
3976 29 ▶ if ( $$in_ref =~ s/$re// ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$in_ref =~ s/$re//) 17 12 29
3977 17 $$out_ref .= $1;
3978 17 return 1;
3979 }
3980 12 my $hmm = get_more_input;
3981 12 ▶ unless ( defined $hmm ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $hmm) 4 8 12
3982 4 $$out_ref = $$in_ref;
3983 4 $$in_ref = '';
3984 4 ▶ return length $$out_ref ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $$out_ref ? : 4 0 4
3985 }
3986 8 ▶ return 0 if $hmm eq 0;
Branch: 1 branch
BranchTrueFalseTotal
if $hmm eq 0 0 8 8
3987 }
3988 }
3989 5 };
3990 }
3991  
3992 =pod
3993  
3994 =item new_appender
3995  
3996 This appends a fixed string to each chunk of data read from the source
3997 scalar or sub. This might be useful if you're writing commands to a
3998 child process that always must end in a fixed string, like "\n":
3999  
4000 run( \@cmd,
4001 '<', new_appender( "\n" ), \&commands,
4002 );
4003  
4004 Here's a typical filter sub that might be created by new_appender():
4005  
4006 sub newline_appender {
4007 my ( $in_ref, $out_ref ) = @_;
4008  
4009 return input_avail && do {
4010 $$out_ref = join( '', $$out_ref, $$in_ref, "\n" );
4011 $$in_ref = '';
4012 1;
4013 }
4014 };
4015  
4016 =cut
4017  
4018 sub new_appender($) {
4019 1 ▶ my ($suffix) = @_;
Subroutine new_appender: called CC=2 SCAR=7.0
Pod documented
4020 1 ▶ croak "\$suffix undefined" unless defined $suffix;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $suffix 0 1 1
4021  
4022 return sub {
4023 10 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.0
4024  
4025 10 ▶ return input_avail && do {
Condition66%2/3
&input_avail() && do { $$out_ref = join('', $$out_ref, $$in_ref, $suffix); $$in_ref = ''; 1 }
!ll&&!rl&&r
703
MC/DC50%1/2
&input_avail() && do { $$out_ref = join('', $$out_ref, $$in_ref, $suffix); $$in_ref = ''; 1 }
&input_avail() do { $$out_ref = join('', $$out_ref, $$in_ref, $suffix); $$in_ref = ''; 1 }
Truth table66%2/3
A && B
A= &input_avail()B= do { $$out_ref = join('', $$out_ref, $$in_ref, $suffix); $$in_ref = ''; 1 }
ABresult
0X0
100
111
4026 3 $$out_ref = join( '', $$out_ref, $$in_ref, $suffix );
4027 3 $$in_ref = '';
4028 3 1;
4029 }
4030 1 };
4031 }
4032  
4033 =item new_string_source
4034  
4035 TODO: Needs confirmation. Was previously undocumented. in this module.
4036  
4037 This is a filter which is exportable. Returns a sub which appends the data passed in to the output buffer and returns 1 if data was appended. 0 if it was an empty string and undef if no data was passed.
4038  
4039 NOTE: Any additional variables passed to new_string_source will be passed to the sub every time it's called and appended to the output.
4040  
4041 =cut
4042  
4043 sub new_string_source {
4044 104 ▶ my $ref;
Subroutine new_string_source: called CC=3 SCAR=13.6
Pod documented
4045 104 ▶ if ( @_ > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) { } 0 104 104
4046 0 $ref = [@_],
4047 }
4048 else {
4049 104 $ref = shift;
4050 }
4051  
4052 return ref $ref eq 'SCALAR'
4053 ? sub {
4054 0 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
4055  
4056 return defined $$ref
4057 0 ▶ ? do {
Branch: 1 branch
BranchTrueFalseTotal
defined $$ref ? : 0 0 0
4058 0 $$out_ref .= $$ref;
4059 0 ▶ my $r = length $$ref ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $$ref ? : 0 0 0
4060 0 $$ref = undef;
4061 0 $r;
4062 }
4063 : undef;
4064 }
4065 : sub {
4066 896 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.0
4067  
4068 return @$ref
4069 896 ▶ ? do {
Branch: 1 branch
BranchTrueFalseTotal
@$ref ? : 325 571 896
4070 325 my $s = shift @$ref;
4071 325 $$out_ref .= $s;
4072 325 ▶ length $s ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $s ? : 117 208 325
4073 }
4074 : undef;
4075 }
4076 104 ▶}
Branch: 1 branch
BranchTrueFalseTotal
ref $ref eq 'SCALAR' ? : 0 104 104
4077  
4078 =item new_string_sink
4079  
4080 TODO: Needs confirmation. Was previously undocumented.
4081  
4082 This is a filter which is exportable. Returns a sub which pops the data out of the input stream and pushes it onto the string.
4083  
4084 =cut
4085  
4086 sub new_string_sink {
4087 104 ▶ my ($string_ref) = @_;
Subroutine new_string_sink: called CC=1 SCAR=0.0
Pod documented
4088  
4089 return sub {
4090 1086 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.0
4091  
4092 1086 ▶ return input_avail && do {
Condition66%2/3
&input_avail() && do { $$string_ref .= $$in_ref; $$in_ref = ''; 1 }
!ll&&!rl&&r
7280358
MC/DC50%1/2
&input_avail() && do { $$string_ref .= $$in_ref; $$in_ref = ''; 1 }
&input_avail() do { $$string_ref .= $$in_ref; $$in_ref = ''; 1 }
Truth table66%2/3
A && B
A= &input_avail()B= do { $$string_ref .= $$in_ref; $$in_ref = ''; 1 }
ABresult
0X0
100
111
4093 358 $$string_ref .= $$in_ref;
4094 358 $$in_ref = '';
4095 358 1;
4096 }
4097 104 };
4098 }
4099  
4100 #=item timeout
4101 #
4102 #This function defines a time interval, starting from when start() is
4103 #called, or when timeout() is called. If all processes have not finished
4104 #by the end of the timeout period, then a "process timed out" exception
4105 #is thrown.
4106 #
4107 #The time interval may be passed in seconds, or as an end time in
4108 #"HH:MM:SS" format (any non-digit other than '.' may be used as
4109 #spacing and punctuation). This is probably best shown by example:
4110 #
4111 # $h->timeout( $val );
4112 #
4113 # $val Effect
4114 # ======================== =====================================
4115 # undef Timeout timer disabled
4116 # '' Almost immediate timeout
4117 # 0 Almost immediate timeout
4118 # 0.000001 timeout > 0.0000001 seconds
4119 # 30 timeout > 30 seconds
4120 # 30.0000001 timeout > 30 seconds
4121 # 10:30 timeout > 10 minutes, 30 seconds
4122 #
4123 #Timeouts are currently evaluated with a 1 second resolution, though
4124 #this may change in the future. This means that setting
4125 #timeout($h,1) will cause a pokey child to be aborted sometime after
4126 #one second has elapsed and typically before two seconds have elapsed.
4127 #
4128 #This sub does not check whether or not the timeout has expired already.
4129 #
4130 #Returns the number of seconds set as the timeout (this does not change
4131 #as time passes, unless you call timeout( val ) again).
4132 #
4133 #The timeout does not include the time needed to fork() or spawn()
4134 #the child processes, though some setup time for the child processes can
4135 #included. It also does not include the length of time it takes for
4136 #the children to exit after they've closed all their pipes to the
4137 #parent process.
4138 #
4139 #=cut
4140 #
4141 #sub timeout {
4142 # my IPC::Run $self = shift;
4143 #
4144 # if ( @_ ) {
4145 # ( $self->{TIMEOUT} ) = @_;
4146 # $self->{TIMEOUT_END} = undef;
4147 # if ( defined $self->{TIMEOUT} ) {
4148 # if ( $self->{TIMEOUT} =~ /[^\d.]/ ) {
4149 # my @f = split( /[^\d\.]+/i, $self->{TIMEOUT} );
4150 # unshift @f, 0 while @f < 3;
4151 # $self->{TIMEOUT} = (($f[0]*60)+$f[1])*60+$f[2];
4152 # }
4153 # elsif ( $self->{TIMEOUT} =~ /^(\d*)(?:\.(\d*))/ ) {
4154 # $self->{TIMEOUT} = $1 + 1;
4155 # }
4156 # $self->_calc_timeout_end if $self->{STATE} >= _started;
4157 # }
4158 # }
4159 # return $self->{TIMEOUT};
4160 #}
4161 #
4162 #
4163 #sub _calc_timeout_end {
4164 # my IPC::Run $self = shift;
4165 #
4166 # $self->{TIMEOUT_END} = defined $self->{TIMEOUT}
4167 # ? time + $self->{TIMEOUT}
4168 # : undef;
4169 #
4170 # ## We add a second because we might be at the very end of the current
4171 # ## second, and we want to guarantee that we don't have a timeout even
4172 # ## one second less then the timeout period.
4173 # ++$self->{TIMEOUT_END} if $self->{TIMEOUT};
4174 #}
4175  
4176 =pod
4177  
4178 =item io
4179  
4180 Takes a filename or filehandle, a redirection operator, optional filters,
4181 and a source or destination (depends on the redirection operator). Returns
4182 an IPC::Run::IO object suitable for harness()ing (including via start()
4183 or run()).
4184  
4185 This is shorthand for
4186  
4187  
4188 require IPC::Run::IO;
4189  
4190 ... IPC::Run::IO->new(...) ...
4191  
4192 =cut
4193  
4194 sub io {
4195 7 ▶ require IPC::Run::IO;
Subroutine io: called CC=1 SCAR=0.0
Pod documented
4196 7 IPC::Run::IO->new(@_);
4197 }
4198  
4199 =pod
4200  
4201 =item timer
4202  
4203 $h = start( \@cmd, \$in, \$out, $t = timer( 5 ) );
4204  
4205 pump $h until $out =~ /expected stuff/ || $t->is_expired;
4206  
4207 Instantiates a non-fatal timer. pump() returns once each time a timer
4208 expires. Has no direct effect on run(), but you can pass a subroutine
4209 to fire when the timer expires.
4210  
4211 See L</timeout> for building timers that throw exceptions on
4212 expiration.
4213  
4214 See L<IPC::Run::Timer/timer> for details.
4215  
4216 =cut
4217  
4218 # Doing the prototype suppresses 'only used once' on older perls.
4219 sub timer;
4220 127 *timer = \&IPC::Run::Timer::timer;
4221  
4222 =pod
4223  
4224 =item timeout
4225  
4226 $h = start( \@cmd, \$in, \$out, $t = timeout( 5 ) );
4227  
4228 pump $h until $out =~ /expected stuff/;
4229  
4230 Instantiates a timer that throws an exception when it expires.
4231 If you don't provide an exception, a default exception that matches
4232 /^IPC::Run: .*timed out/ is thrown by default. You can pass in your own
4233 exception scalar or reference:
4234  
4235 $h = start(
4236 \@cmd, \$in, \$out,
4237 $t = timeout( 5, exception => 'slowpoke' ),
4238 );
4239  
4240 or set the name used in debugging message and in the default exception
4241 string:
4242  
4243 $h = start(
4244 \@cmd, \$in, \$out,
4245 timeout( 50, name => 'process timer' ),
4246 $stall_timer = timeout( 5, name => 'stall timer' ),
4247 );
4248  
4249 pump $h until $out =~ /started/;
4250  
4251 $in = 'command 1';
4252 $stall_timer->start;
4253 pump $h until $out =~ /command 1 finished/;
4254  
4255 $in = 'command 2';
4256 $stall_timer->start;
4257 pump $h until $out =~ /command 2 finished/;
4258  
4259 $in = 'very slow command 3';
4260 $stall_timer->start( 10 );
4261 pump $h until $out =~ /command 3 finished/;
4262  
4263 $stall_timer->start( 5 );
4264 $in = 'command 4';
4265 pump $h until $out =~ /command 4 finished/;
4266  
4267 $stall_timer->reset; # Prevent restarting or expirng
4268 finish $h;
4269  
4270 See L</timer> for building non-fatal timers.
4271  
4272 See L<IPC::Run::Timer/timer> for details.
4273  
4274 =cut
4275  
4276 # Doing the prototype suppresses 'only used once' on older perls.
4277 sub timeout;
4278 127 *timeout = \&IPC::Run::Timer::timeout;
4279  
4280 =pod
4281  
4282 =back
4283  
4284 =head1 FILTER IMPLEMENTATION FUNCTIONS
4285  
4286 These functions are for use from within filters.
4287  
4288 =over
4289  
4290 =item input_avail
4291  
4292 Returns TRUE if input is available. If none is available, then
4293 &get_more_input is called and its result is returned.
4294  
4295 This is usually used in preference to &get_more_input so that the
4296 calling filter removes all data from the $in_ref before more data
4297 gets read in to $in_ref.
4298  
4299 C<input_avail> is usually used as part of a return expression:
4300  
4301 return input_avail && do {
4302 ## process the input just gotten
4303 1;
4304 };
4305  
4306 This technique allows input_avail to return the undef or 0 that a
4307 filter normally returns when there's no input to process. If a filter
4308 stores intermediate values, however, it will need to react to an
4309 undef:
4310  
4311 my $got = input_avail;
4312 if ( ! defined $got ) {
4313 ## No more input ever, flush internal buffers to $out_ref
4314 }
4315 return $got unless $got;
4316 ## Got some input, move as much as need be
4317 return 1 if $added_to_out_ref;
4318  
4319 =cut
4320  
4321 sub input_avail() {
4322 confess "Undefined FBUF ref for $filter_num+1"
4323 2671 ▶ unless defined $filter_op->{FBUFS}->[ $filter_num + 1 ];
Subroutine input_avail: called CC=3 SCAR=11.1
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless defined $IPC::Run::filter_op->{"FBUFS"}[$IPC::Run::filter_num + 1] 0 2671 2671
4324 2671 ▶ length ${ $filter_op->{FBUFS}->[ $filter_num + 1 ] } || get_more_input;
Branch: 1 branch
BranchTrueFalseTotal
length ${$IPC::Run::filter_op->{"FBUFS"}[$IPC::Run::filter_num + 1];} or &get_more_input() 2154 517 2671
4325 }
4326  
4327 =pod
4328  
4329 =item get_more_input
4330  
4331 This is used to fetch more input in to the input variable. It returns
4332 undef if there will never be any more input, 0 if there is none now,
4333 but there might be in the future, and TRUE if more input was gotten.
4334  
4335 C<get_more_input> is usually used as part of a return expression,
4336 see L</input_avail> for more information.
4337  
4338 =cut
4339  
4340 ##
4341 ## Filter implementation interface
4342 ##
4343 sub get_more_input() {
4344 10169 ▶ ++$filter_num;
Subroutine get_more_input: called CC=3 SCAR=11.2
Pod documented
4345 10169 my $r = eval {
4346 confess "get_more_input() called and no more filters in chain"
4347 10169 ▶ unless defined $filter_op->{FILTERS}->[$filter_num];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $IPC::Run::filter_op->{"FILTERS"}[$IPC::Run::filter_num] 0 10169 10169
4348 $filter_op->{FILTERS}->[$filter_num]->(
4349 $filter_op->{FBUFS}->[ $filter_num + 1 ],
4350 10169 $filter_op->{FBUFS}->[$filter_num],
4351 ); # if defined ${$filter_op->{FBUFS}->[$filter_num+1]};
4352 };
4353 10169 --$filter_num;
4354 10169 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 10169 10169
4355 10169 return $r;
4356 }
4357  
4358 127 1;
4359  
4360 =pod
4361  
4362 =back
4363  
4364 =head1 TODO
4365  
4366 These will be addressed as needed and as time allows.
4367  
4368 Stall timeout.
4369  
4370 Expose a list of child process objects. When I do this,
4371 each child process is likely to be blessed into IPC::Run::Proc.
4372  
4373 $kid->abort(), $kid->kill(), $kid->signal( $num_or_name ).
4374  
4375 Write tests for /(full_)?results?/ subs.
4376  
4377 Currently, pump() and run() only work on systems where select() works on the
4378 filehandles returned by pipe(). This does *not* include ActiveState on Win32,
4379 although it does work on cygwin under Win32 (thought the tests whine a bit).
4380 I'd like to rectify that, suggestions and patches welcome.
4381  
4382 Likewise start() only fully works on fork()/exec() machines (well, just
4383 fork() if you only ever pass perl subs as subprocesses). There's
4384 some scaffolding for calling Open3::spawn_with_handles(), but that's
4385 untested, and not that useful with limited select().
4386  
4387 Support for C<\@sub_cmd> as an argument to a command which
4388 gets replaced with /dev/fd or the name of a temporary file containing foo's
4389 output. This is like <(sub_cmd ...) found in bash and csh (IIRC).
4390  
4391 Allow multiple harnesses to be combined as independent sets of processes
4392 in to one 'meta-harness'.
4393  
4394 Allow a harness to be passed in place of an \@cmd. This would allow
4395 multiple harnesses to be aggregated.
4396  
4397 Ability to add external file descriptors w/ filter chains and endpoints.
4398  
4399 Ability to add timeouts and timing generators (i.e. repeating timeouts).
4400  
4401 High resolution timeouts.
4402  
4403 =head1 Win32 LIMITATIONS
4404  
4405 =over
4406  
4407 =item argument-passing rules are program-specific
4408  
4409 Win32 programs receive all arguments in a single "command line" string.
4410 IPC::Run assembles this string so programs using L<standard command line parsing
4411 rules|https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args#parsing-c-command-line-arguments>
4412 will see an C<argv> that matches the array reference specifying the command.
4413 Some programs use different rules to parse their command line. Notable examples
4414 include F<cmd.exe>, F<cscript.exe>, and Cygwin programs called from non-Cygwin
4415 programs. Use L<IPC::Run::Win32Process> to call these and other nonstandard
4416 programs.
4417  
4418 =item batch files
4419  
4420 Properly escaping a batch file argument depends on how the script will use that
4421 argument, because some uses experience multiple levels of caret (escape
4422 character) removal. Avoid calling batch files with arguments, particularly when
4423 the argument values originate outside your program or contain non-alphanumeric
4424 characters. Perl scripts and PowerShell scripts are sound alternatives. If you
4425 do use batch file arguments, IPC::Run escapes them so the batch file can pass
4426 them, unquoted, to a program having standard command line parsing rules. If the
4427 batch file enables delayed environment variable expansion, it must disable that
4428 feature before expanding its arguments. For example, if F<foo.cmd> contains
4429 C<perl %*>, C<run ['foo.cmd', @list]> will create a Perl process in which
4430 C<@ARGV> matches C<@list>. Prepending a C<setlocal enabledelayedexpansion> line
4431 would make the batch file malfunction, silently. Another silent-malfunction
4432 example is C<run ['outer.bat', @list]> for F<outer.bat> containing C<foo.cmd
4433 %*>.
4434  
4435 =item Fails on Win9X
4436  
4437 If you want Win9X support, you'll have to debug it or fund me because I
4438 don't use that system any more. The Win32 subsysem has been extended to
4439 use temporary files in simple run() invocations and these may actually
4440 work on Win9X too, but I don't have time to work on it.
4441  
4442 =item May deadlock on Win2K (but not WinNT4 or WinXPPro)
4443  
4444 Spawning more than one subprocess on Win2K causes a deadlock I haven't
4445 figured out yet, but simple uses of run() often work. Passes all tests
4446 on WinXPPro and WinNT.
4447  
4448 =item no support yet for <pty< and >pty>
4449  
4450 These are likely to be implemented as "<" and ">" with binmode on, not
4451 sure.
4452  
4453 =item no support for file descriptors higher than 2 (stderr)
4454  
4455 Win32 only allows passing explicit fds 0, 1, and 2. If you really, really need to pass file handles, us Win32API:: GetOsFHandle() or ::FdGetOsFHandle() to
4456 get the integer handle and pass it to the child process using the command
4457 line, environment, stdin, intermediary file, or other IPC mechanism. Then
4458 use that handle in the child (Win32API.pm provides ways to reconstitute
4459 Perl file handles from Win32 file handles).
4460  
4461 =item no support for subroutine subprocesses (CODE refs)
4462  
4463 Can't fork(), so the subroutines would have no context, and closures certainly
4464 have no meaning
4465  
4466 Perhaps with Win32 fork() emulation, this can be supported in a limited
4467 fashion, but there are other very serious problems with that: all parent
4468 fds get dup()ed in to the thread emulating the forked process, and that
4469 keeps the parent from being able to close all of the appropriate fds.
4470  
4471 =item no support for init => sub {} routines.
4472  
4473 Win32 processes are created from scratch, there is no way to do an init
4474 routine that will affect the running child. Some limited support might
4475 be implemented one day, do chdir() and %ENV changes can be made.
4476  
4477 =item signals
4478  
4479 Win32 does not fully support signals. signal() is likely to cause errors
4480 unless sending a signal that Perl emulates, and C<kill_kill()> is immediately
4481 fatal (there is no grace period).
4482  
4483 =item C<$?> cannot represent all Win32 exit codes
4484  
4485 Prefer C<full_result( ... )>, C<result( ... )>, or other IPC::Run methods.
4486  
4487 =item helper processes
4488  
4489 IPC::Run uses helper processes, one per redirected file, to adapt between the
4490 anonymous pipe connected to the child and the TCP socket connected to the
4491 parent. This is a waste of resources and will change in the future to either
4492 use threads (instead of helper processes) or a WaitForMultipleObjects call
4493 (instead of select). Please contact me if you can help with the
4494 WaitForMultipleObjects() approach; I haven't figured out how to get at it
4495 without C code.
4496  
4497 =item shutdown pause
4498  
4499 There seems to be a pause of up to 1 second between when a child program exits
4500 and the corresponding sockets indicate that they are closed in the parent.
4501 Not sure why.
4502  
4503 =item binmode
4504  
4505 binmode is not supported yet. The underpinnings are implemented, just ask
4506 if you need it.
4507  
4508 =item IPC::Run::IO
4509  
4510 IPC::Run::IO objects can be used on Unix to read or write arbitrary files. On
4511 Win32, they will need to use the same helper processes to adapt from
4512 non-select()able filehandles to select()able ones (or perhaps
4513 WaitForMultipleObjects() will work with them, not sure).
4514  
4515 =item startup race conditions
4516  
4517 There seems to be an occasional race condition between child process startup
4518 and pipe closings. It seems like if the child is not fully created by the time
4519 CreateProcess returns and we close the TCP socket being handed to it, the
4520 parent socket can also get closed. This is seen with the Win32 pumper
4521 applications, not the "real" child process being spawned.
4522  
4523 I assume this is because the kernel hasn't gotten around to incrementing the
4524 reference count on the child's end (since the child was slow in starting), so
4525 the parent's closing of the child end causes the socket to be closed, thus
4526 closing the parent socket.
4527  
4528 Being a race condition, it's hard to reproduce, but I encountered it while
4529 testing this code on a drive share to a samba box. In this case, it takes
4530 t/run.t a long time to spawn its child processes (the parent hangs in the
4531 first select for several seconds until the child emits any debugging output).
4532  
4533 I have not seen it on local drives, and can't reproduce it at will,
4534 unfortunately. The symptom is a "bad file descriptor in select()" error, and,
4535 by turning on debugging, it's possible to see that select() is being called on
4536 a no longer open file descriptor that was returned from the _socket() routine
4537 in Win32Helper. There's a new confess() that checks for this ("PARENT_HANDLE
4538 no longer open"), but I haven't been able to reproduce it (typically).
4539  
4540 =back
4541  
4542 =head1 LIMITATIONS
4543  
4544 On Unix, requires a system that supports C<waitpid( $pid, WNOHANG )> so
4545 it can tell if a child process is still running.
4546  
4547 PTYs don't seem to be non-blocking on some versions of Solaris. Here's a
4548 test script contributed by Borislav Deianov <borislav@ensim.com> to see
4549 if you have the problem. If it dies, you have the problem.
4550  
4551 #!/usr/bin/perl
4552  
4553 use IPC::Run qw(run);
4554 use Fcntl;
4555 use IO::Pty;
4556  
4557 sub makecmd {
4558 return ['perl', '-e',
4559 '<STDIN>, print "\n" x '.$_[0].'; while(<STDIN>){last if /end/}'];
4560 }
4561  
4562 #pipe R, W;
4563 #fcntl(W, F_SETFL, O_NONBLOCK);
4564 #while (syswrite(W, "\n", 1)) { $pipebuf++ };
4565 #print "pipe buffer size is $pipebuf\n";
4566 my $pipebuf=4096;
4567 my $in = "\n" x ($pipebuf * 2) . "end\n";
4568 my $out;
4569  
4570 $SIG{ALRM} = sub { die "Never completed!\n" };
4571  
4572 print "reading from scalar via pipe...";
4573 alarm( 2 );
4574 run(makecmd($pipebuf * 2), '<', \$in, '>', \$out);
4575 alarm( 0 );
4576 print "done\n";
4577  
4578 print "reading from code via pipe... ";
4579 alarm( 2 );
4580 run(makecmd($pipebuf * 3), '<', sub { $t = $in; undef $in; $t}, '>', \$out);
4581 alarm( 0 );
4582 print "done\n";
4583  
4584 $pty = IO::Pty->new();
4585 $pty->blocking(0);
4586 $slave = $pty->slave();
4587 while ($pty->syswrite("\n", 1)) { $ptybuf++ };
4588 print "pty buffer size is $ptybuf\n";
4589 $in = "\n" x ($ptybuf * 3) . "end\n";
4590  
4591 print "reading via pty... ";
4592 alarm( 2 );
4593 run(makecmd($ptybuf * 3), '<pty<', \$in, '>', \$out);
4594 alarm(0);
4595 print "done\n";
4596  
4597 No support for ';', '&&', '||', '{ ... }', etc: use perl's, since run()
4598 returns TRUE when the command exits with a 0 result code.
4599  
4600 Does not provide shell-like string interpolation.
4601  
4602 No support for C<cd>, C<setenv>, or C<export>: do these in an init() sub
4603  
4604 run(
4605 \cmd,
4606 ...
4607 init => sub {
4608 chdir $dir or die $!;
4609 $ENV{FOO}='BAR'
4610 }
4611 );
4612  
4613 Timeout calculation does not allow absolute times, or specification of
4614 days, months, etc.
4615  
4616 B<WARNING:> Function coprocesses (C<run \&foo, ...>) suffer from two
4617 limitations. The first is that it is difficult to close all filehandles the
4618 child inherits from the parent, since there is no way to scan all open
4619 FILEHANDLEs in Perl and it both painful and a bit dangerous to close all open
4620 file descriptors with C<POSIX::close()>. Painful because we can't tell which
4621 fds are open at the POSIX level, either, so we'd have to scan all possible fds
4622 and close any that we don't want open (normally C<exec()> closes any
4623 non-inheritable but we don't C<exec()> for &sub processes.
4624  
4625 The second problem is that Perl's DESTROY subs and other on-exit cleanup gets
4626 run in the child process. If objects are instantiated in the parent before the
4627 child is forked, the DESTROY will get run once in the parent and once in
4628 the child. When coprocess subs exit, POSIX::_exit is called to work around this,
4629 but it means that objects that are still referred to at that time are not
4630 cleaned up. So setting package vars or closure vars to point to objects that
4631 rely on DESTROY to affect things outside the process (files, etc), will
4632 lead to bugs.
4633  
4634 I goofed on the syntax: "<pipe" vs. "<pty<" and ">filename" are both
4635 oddities.
4636  
4637 =head1 TODO
4638  
4639 =over
4640  
4641 =item Allow one harness to "adopt" another:
4642  
4643 $new_h = harness \@cmd2;
4644 $h->adopt( $new_h );
4645  
4646 =item Close all filehandles not explicitly marked to stay open.
4647  
4648 The problem with this one is that there's no good way to scan all open
4649 FILEHANDLEs in Perl, yet you don't want child processes inheriting handles
4650 willy-nilly.
4651  
4652 =back
4653  
4654 =head1 INSPIRATION
4655  
4656 Well, select() and waitpid() badly needed wrapping, and open3() isn't
4657 open-minded enough for me.
4658  
4659 The shell-like API inspired by a message Russ Allbery sent to perl5-porters,
4660 which included:
4661  
4662 I've thought for some time that it would be
4663 nice to have a module that could handle full Bourne shell pipe syntax
4664 internally, with fork and exec, without ever invoking a shell. Something
4665 that you could give things like:
4666  
4667 pipeopen (PIPE, [ qw/cat file/ ], '|', [ 'analyze', @args ], '>&3');
4668  
4669 Message ylln51p2b6.fsf@windlord.stanford.edu, on 2000/02/04.
4670  
4671 =head1 SUPPORT
4672  
4673 Bugs should always be submitted via the GitHub bug tracker
4674  
4675 L<https://github.com/toddr/IPC-Run/issues>
4676  
4677 =head1 AUTHORS
4678  
4679 Adam Kennedy <adamk@cpan.org>
4680  
4681 Barrie Slaymaker <barries@slaysys.com>
4682  
4683 =head1 COPYRIGHT
4684  
4685 Some parts copyright 2008 - 2009 Adam Kennedy.
4686  
4687 Copyright 1999 Barrie Slaymaker.
4688  
4689 You may distribute under the terms of either the GNU General Public
4690 License or the Artistic License, as specified in the README file.
4691  
4692 =cut
« blib/lib/IPC/Run/Win32Helper.pm ↑ Summary blib/lib/IPC/Run/Win32IO.pm »