blib/lib/IPC/Run.pm

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