blib/lib/IPC/Run.pm

filter: Statementstmt 87.1% 1193 / 1369 Branchbran 61.7% 615 / 996 Conditioncond 62.2% 241 / 387 MC/DCmcdc 40.8% 87 / 213 Subroutinesub 97.8% 93 / 95 Podpod 100% 33 / 33 totaltotal 73.1% 2262 / 3093 CC 685 SCAR 49.8
CC
685
Cov
74%
_select_loop
775.2
harness
179.8
_open_pipes
146.9
CRAP 145.8
« blib/lib/IPC/Run/Win32Helper.pm ↑ Summary blib/lib/IPC/Run/Win32IO.pm »
1 package IPC::Run;
2 228 ▶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 228 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
1161 228 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
1162 228 ▶use Exporter ();
Subroutine BEGIN: called CC=1 SCAR=0.0
1163 228 ▶use vars qw{$VERSION @ISA @FILTER_IMP @FILTERS @API @EXPORT_OK %EXPORT_TAGS};
Subroutine BEGIN: called CC=1 SCAR=0.0
1164  
1165 BEGIN {
1166 228 ▶ $VERSION = '20260401.0';
Subroutine BEGIN: called CC=1 SCAR=0.0
1167 228 @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 228 @FILTER_IMP = qw( input_avail get_more_input );
1173 228 @FILTERS = qw(
1174 new_appender
1175 new_chunker
1176 new_string_source
1177 new_string_sink
1178 );
1179 228 @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 228 @EXPORT_OK = ( @API, @FILTER_IMP, @FILTERS, qw( Win32_MODE ) );
1189 228 %EXPORT_TAGS = (
1190 'filter_imp' => \@FILTER_IMP,
1191 'all' => \@EXPORT_OK,
1192 'filters' => \@FILTERS,
1193 'api' => \@API,
1194 );
1195  
1196 }
1197  
1198 228 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
1199 228 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
1200 228 ▶use IPC::Run::Debug;
Subroutine BEGIN: called CC=1 SCAR=0.0
1201 228 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
1202 228 ▶use Fcntl;
Subroutine BEGIN: called CC=1 SCAR=0.0
1203 228 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
1204  
1205 BEGIN {
1206 228 ▶ if ( $] < 5.008 ) { require Symbol; }
Subroutine BEGIN: called CC=2 SCAR=9.2
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.008") 0 228 228
1207 }
1208 228 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
1209 228 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
1210 228 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
1211 228 require IPC::Run::IO;
1212 228 require IPC::Run::Timer;
1213  
1214 228 ▶use constant Win32_MODE => $^O =~ /os2|Win32/i;
Subroutine BEGIN: called CC=1 SCAR=0.0
1215  
1216 BEGIN {
1217 228 ▶ if (Win32_MODE) {
Subroutine BEGIN: called CC=6 SCAR=25.9
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 228 228
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 228 ▶ eval "use File::Basename; 1;" or die $!;
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
eval "use File::Basename; 1;" or die $! 0 228 228
1224 }
1225 }
1226  
1227 sub input_avail();
1228 sub get_more_input();
1229  
1230 ###############################################################################
1231  
1232 ##
1233 ## Error constants, not too locale-dependent
1234 228 ▶use vars qw( $_EIO $_EAGAIN );
Subroutine BEGIN: called CC=1 SCAR=0.0
1235 228 ▶use Errno qw( EIO EAGAIN EPIPE );
Subroutine BEGIN: called CC=1 SCAR=0.0
1236  
1237 BEGIN {
1238 228 ▶ local $!;
Subroutine BEGIN: called CC=1 SCAR=0.0
1239 228 $! = EIO;
1240 228 $_EIO = qr/^$!/;
1241 228 $! = EAGAIN;
1242 228 $_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 228 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 228 ▶use vars qw( $cur_self );
Subroutine BEGIN: called CC=1 SCAR=0.0
1272  
1273 sub _debug_fd {
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 3709 ▶ my $stderr_fd = eval { fileno STDERR };
Subroutine _debug_fd: called CC=7 SCAR=29.9
1280  
1281 3709 ▶ return $stderr_fd unless defined $cur_self;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $IPC::Run::cur_self 0 3709 3709
1282  
1283 3709 ▶ if ( _debugging && !defined $cur_self->{DEBUG_FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging() and not defined $IPC::Run::cur_self->{"DEBUG_FD"}) 0 3709 3709
Condition33%1/3
&_debugging() and not defined $IPC::Run::cur_self->{"DEBUG_FD"}
!ll&&!rl&&r
370900
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 3709 ▶ return $stderr_fd unless defined $cur_self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $IPC::Run::cur_self->{"DEBUG_FD"} 3709 0 3709
1295  
1296 0 return $cur_self->{DEBUG_FD};
1297 }
1298  
1299 sub DESTROY {
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 2465 ▶ my IPC::Run $self = shift;
Subroutine DESTROY: called CC=4 SCAR=13.9
1304 2465 ▶ POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"DEBUG_FD"} 0 2465 2465
1305 2465 $self->{DEBUG_FD} = undef;
1306  
1307 2465 for my $kid ( @{$self->{KIDS}} ) {
1308 2382 for my $op ( @{$kid->{OPS}} ) {
1309 4079 delete $op->{FILTERS};
1310 }
1311 }
1312 }
1313  
1314 ##
1315 ## Support routines (NOT METHODS)
1316 ##
1317 my %cmd_cache;
1318 228 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 sub clearcache {
1338 10 ▶ %cmd_cache = ();
Subroutine clearcache: called CC=1 SCAR=0.0
Pod documented
1339 10 $_cmd_cache_path = '';
1340 10 return;
1341 }
1342  
1343 sub _search_path {
1344 2145 ▶ my ($cmd_name) = @_;
Subroutine _search_path: called CC=43 SCAR=42.6
1345 2145 ▶ croak "command name is undefined or empty"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cmd_name and length $cmd_name 2 2143 2145
Condition100%3/3
defined $cmd_name and length $cmd_name
!ll&&!rl&&r
112143
MC/DC100%2/2
defined $cmd_name and length $cmd_name
defined $cmd_name length $cmd_name
Truth table100%3/3
A and B
A= defined $cmd_nameB= length $cmd_name
ABresult
0X0
100
111
1346 unless defined $cmd_name && length $cmd_name;
1347 2143 ▶ 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) 1706 437 2143
Condition66%2/3
"File::Spec"->file_name_is_absolute($cmd_name) and -x $cmd_name
!ll&&!rl&&r
43701706
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 1706 ▶ _debug "'", $cmd_name, "' is absolute"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1706 1706
1349 if _debugging_details;
1350 1706 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 630 ▶ $_ = "." unless length $_;
Branch: 1 branch
BranchTrueFalseTotal
unless length $_ 0 630 630
1408 630 push @searched_in, $_;
1409  
1410 630 my $prospect = File::Spec->catfile( $_, $cmd_name );
1411 630 my @prospects;
1412  
1413 @prospects =
1414 ( Win32_MODE && !( -f $prospect && -x _ ) )
1415 630 ▶ ? map "$prospect$_", split /;/, $ENV{PATHEXT} || ".COM;.BAT;.EXE"
Branch: 1 branch
BranchTrueFalseTotal
&Win32_MODE() && !(-f $prospect && -x _) ? : 0 630 630
Condition12%1/8
&Win32_MODE() and not -f $prospect && -x _
!ll&&!rl&&r
63000
-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 630 for my $found (@prospects) {
1419 630 ▶ if ( -f $found && -x _ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $found and -x _) 102 528 630
Condition66%2/3
-f $found and -x _
!ll&&!rl&&r
5280102
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 sub _debugstrings {
1438 0 ▶ my $operand = shift;
Subroutine _debugstrings: not called CC=7 SCAR=40.3
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 11616 ▶sub _empty($) { !( defined $_[0] && length $_[0] ) }
Subroutine _empty: called CC=2 SCAR=6.9
Condition100%3/3
defined $_[0] && length $_[0]
!ll&&!rl&&r
23717419638
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 sub _close {
1466 12255 ▶ confess 'undef' unless defined $_[0];
Subroutine _close: called CC=13 SCAR=41.7
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 12255 12255
1467 12255 ▶ my $fd = $_[0] =~ /^\d+$/ ? $_[0] : fileno $_[0];
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /^\d+$/ ? : 12255 0 12255
1468 12255 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) 0 12255 12255
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 12255 my $r = POSIX::close $fd;
1503 12255 ▶ $r = $r ? '' : " ERROR $!";
Branch: 1 branch
BranchTrueFalseTotal
$r ? : 12184 71 12255
1504 12255 delete $fds{$fd};
1505 12255 ▶ _debug "close( $fd ) = " . ( $r || 0 ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 12255 12255
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 sub _dup {
1509 2269 ▶ confess 'undef' unless defined $_[0];
Subroutine _dup: called CC=5 SCAR=17.0
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 2269 2269
1510 2269 my $r = POSIX::dup( $_[0] );
1511 2269 ▶ croak "$!: dup( $_[0] )" unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 0 2269 2269
1512 2269 ▶ $r = 0 if $r eq '0 but true';
Branch: 1 branch
BranchTrueFalseTotal
if $r eq "0 but true" 0 2269 2269
1513 2269 ▶ _debug "dup( $_[0] ) = $r" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2269 2269
1514 2269 $fds{$r} = {};
1515 2269 return $r;
1516 }
1517  
1518 sub _dup2_rudely {
1519 361 ▶ confess 'undef' unless defined $_[0] && defined $_[1];
Subroutine _dup2_rudely: called CC=6 SCAR=19.1
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and defined $_[1] 0 361 361
Condition33%1/3
defined $_[0] and defined $_[1]
!ll&&!rl&&r
00361
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 361 my $r = POSIX::dup2( $_[0], $_[1] );
1521 361 ▶ croak "$!: dup2( $_[0], $_[1] )" unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 0 361 361
1522 361 ▶ $r = 0 if $r eq '0 but true';
Branch: 1 branch
BranchTrueFalseTotal
if $r eq "0 but true" 122 239 361
1523 361 ▶ _debug "dup2( $_[0], $_[1] ) = $r" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 361 361
1524 361 $fds{$r} = {};
1525 361 return $r;
1526 }
1527  
1528 sub _exec {
1529 181 ▶ confess 'undef passed' if grep !defined, @_;
Subroutine _exec: called CC=3 SCAR=11.4
Branch: 1 branch
BranchTrueFalseTotal
if grep((!defined($_)), @_) 0 181 181
1530  
1531 # exec @_ or croak "$!: exec( " . join( ', ', @_ ) . " )";
1532 181 ▶ _debug 'exec()ing ', join " ", map "'$_'", @_ if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 181 181
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 181 exec { $_[0] } @_;
1548  
1549 # }
1550 # croak "$!: exec( " . join( ', ', map "'$_'", @_ ) . " )";
1551 ## Fall through so $! can be reported to parent.
1552 }
1553  
1554 sub _sysopen {
1555 264 ▶ confess 'undef' unless defined $_[0] && defined $_[1];
Subroutine _sysopen: called CC=6 SCAR=19.1
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and defined $_[1] 0 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 sub _pipe {
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 5343 ▶ my ( $r, $w ) = POSIX::pipe;
Subroutine _pipe: called CC=3 SCAR=11.3
1576 5343 ▶ croak "$!: pipe()" unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 0 5343 5343
1577 5343 ▶ _debug "pipe() = ( $r, $w ) " if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 5343 5343
1578 5343 @fds{$r, $w} = ( {}, {} );
1579 5343 return ( $r, $w );
1580 }
1581  
1582 sub _pipe_nb {
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 1133 ▶ local ( *R, *W );
Subroutine _pipe_nb: called CC=7 SCAR=20.5
1588 1133 my $f = pipe( R, W );
1589 1133 ▶ croak "$!: pipe()" unless defined $f;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $f 0 1133 1133
1590 1133 my ( $r, $w ) = ( fileno R, fileno W );
1591 1133 ▶ _debug "pipe_nb pipe() = ( $r, $w )" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1133 1133
1592 1133 ▶ unless (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&Win32_MODE()) 1133 0 1133
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 1133 my $fres = fcntl( W, &F_SETFL, O_WRONLY | O_NONBLOCK );
1596 1133 ▶ croak "$!: fcntl( $w, F_SETFL, O_NONBLOCK )" unless $fres;
Branch: 1 branch
BranchTrueFalseTotal
unless $fres 0 1133 1133
1597 1133 ▶ _debug "fcntl( $w, F_SETFL, O_NONBLOCK )" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1133 1133
1598 }
1599 1133 ( $r, $w ) = ( _dup($r), _dup($w) );
1600 1133 ▶ _debug "pipe_nb() = ( $r, $w )" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1133 1133
1601 1133 return ( $r, $w );
1602 }
1603  
1604 sub _pty {
1605 35 ▶ require IO::Pty;
Subroutine _pty: called CC=4 SCAR=14.2
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 )") 0 35 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 sub _read {
1617 6739 ▶ confess 'undef' unless defined $_[0];
Subroutine _read: called CC=7 SCAR=19.6
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 6739 6739
1618 6739 my $s = '';
1619 6739 my $r;
1620 do {
1621 6740 $r = POSIX::read( $_[0], $s, 10_000 );
1622 6739 ▶ } while ( !defined($r) && $!{EINTR} );
Branch: 1 branch
BranchTrueFalseTotal
not defined $r and $!{"EINTR"} and do { do { $r = POSIX::read($_[0], $s, 10000) } } 1 6739 6740
Condition100%3/3
not defined $r and $!{"EINTR"}
!ll&&!rl&&r
6718211
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 6739 ▶ croak "$!: read( $_[0] )" unless defined($r);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 21 6718 6739
1624 6718 ▶ $r ||= 0;
Condition50%1/2
$r ||= 0
l!l
67180
MC/DC0%0/1
$r ||= 0
$r
Truth table50%1/2
A
A= $r
Aresult
11
00
1625 6718 ▶ _debug "read( $_[0] ) = $r chars '$s'" if _debugging_data;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 6718 6718
1626 6718 return $s;
1627 }
1628  
1629 ## A METHOD, not a function.
1630 sub _spawn {
1631 2398 ▶ my IPC::Run $self = shift;
Subroutine _spawn: called CC=14 SCAR=27.3
1632 2398 my ($kid) = @_;
1633  
1634 croak "Can't spawn IPC::Run::Win32Process except on Win32"
1635 2398 ▶ if UNIVERSAL::isa( $kid->{VAL}, 'IPC::Run::Win32Process' );
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($kid->{"VAL"}, "IPC::Run::Win32Process") 0 2398 2398
1636  
1637 2398 ▶ _debug "opening sync pipe ", $kid->{PID} if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2398 2398
1638 2398 my $sync_reader_fd;
1639 2398 ( $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 2398 my $coderef_err_reader_fd;
1646 2398 ▶ if ( ref $kid->{VAL} eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $kid->{"VAL"} eq "CODE") 346 2052 2398
1647 346 ( $coderef_err_reader_fd, $self->{CODEREF_ERR_FD} ) = _pipe;
1648 }
1649  
1650 2398 $kid->{PID} = fork();
1651 2398 ▶ croak "$! during fork" unless defined $kid->{PID};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kid->{"PID"} 0 2398 2398
1652  
1653 2398 ▶ unless ( $kid->{PID} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($kid->{"PID"}) 184 2214 2398
1654 184 ▶ if ( $self->{_sigusr1_after_fork} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_sigusr1_after_fork"}) 0 184 184
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 184 ▶ POSIX::close $coderef_err_reader_fd if defined $coderef_err_reader_fd;
Branch: 1 branch
BranchTrueFalseTotal
if defined $coderef_err_reader_fd 3 181 184
1663 ## _do_kid_and_exit closes sync_reader_fd since it closes all unwanted and
1664 ## unloved fds.
1665 184 $self->_do_kid_and_exit($kid);
1666 }
1667 2214 ▶ _debug "fork() = ", $kid->{PID} if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2214 2214
1668  
1669 ## Close the child's writer end of the error pipe in the parent.
1670 2214 ▶ if ( defined $self->{CODEREF_ERR_FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"CODEREF_ERR_FD"}) 343 1871 2214
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 2214 _close $self->{SYNC_WRITER_FD};
1677 2214 my $sync_pulse = _read $sync_reader_fd;
1678 2214 _close $sync_reader_fd;
1679  
1680 2214 ▶ if ( !defined $sync_pulse || length $sync_pulse ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $sync_pulse or length $sync_pulse) 2 2212 2214
Condition66%2/3
not defined $sync_pulse or length $sync_pulse
l!l&&r!l&&!r
022212
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 2212 return $kid->{PID};
1692 }
1693  
1694 sub _write {
1695 898 ▶ confess 'undef' unless defined $_[0] && defined $_[1];
Subroutine _write: called CC=7 SCAR=23.8
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and defined $_[1] 0 898 898
Condition33%1/3
defined $_[0] and defined $_[1]
!ll&&!rl&&r
00898
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 898 my $r = POSIX::write( $_[0], $_[1], length $_[1] );
1697 898 ▶ unless ( defined $r ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $r) 231 667 898
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 667 ▶ _debug "write( $_[0], '$_[1]' ) = $r" if _debugging_data;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 667 667
1703 667 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 228 ▶use vars qw( $in_run ); ## No, not Enron;)
Subroutine BEGIN: called CC=1 SCAR=0.0
1733  
1734 sub run {
1735 2172 ▶ local $in_run = 1; ## Allow run()-only optimizations.
Subroutine run: called CC=2 SCAR=6.9
Pod documented
1736 2172 my IPC::Run $self = start(@_);
1737 1855 my $r = eval {
1738 1855 $self->{clear_ins} = 0;
1739 1855 $self->finish;
1740 };
1741 1855 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 45 1810 1855
1742 45 my $x = $@;
1743 45 $self->kill_kill;
1744 45 die $x;
1745 }
1746 1810 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 sub signal {
1797 69 ▶ my IPC::Run $self = shift;
Subroutine signal: called CC=9 SCAR=25.6
Pod documented
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"}]) 0 28 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 sub kill_kill {
1861 63 ▶ my IPC::Run $self = shift;
Subroutine kill_kill: called CC=11 SCAR=24.2
Pod documented
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 71 select undef, undef, undef, $delay;
1894 71 $accum_delay += $delay;
1895  
1896 71 $self->reap_nb;
1897 71 ▶ last unless $self->_running_kids;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_running_kids 63 8 71
1898  
1899 8 ▶ if ( $accum_delay >= $grace * 0.8 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($accum_delay >= $grace * "0.8") 1 7 8
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 7 $delay *= 2;
1915 7 ▶ $delay = 0.5 if $delay >= 0.5;
Branch: 1 branch
BranchTrueFalseTotal
if $delay >= "0.5" 2 5 7
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 228 my $harness_id = 0;
1951  
1952 sub harness {
1953 2695 ▶ my $options;
Subroutine harness: called CC=126 SCAR=51.9
Pod documented
1954 2695 ▶ if ( @_ && ref $_[-1] eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ref $_[-1] eq "HASH") 0 2695 2695
Condition66%2/3
@_ and ref $_[-1] eq "HASH"
!ll&&!rl&&r
11625790
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 2695 my @args;
1964 2695 ▶ if ( @_ == 1 && !ref $_[0] ) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ == 1 and not ref $_[0]) { } 105 2590 2695
elsif (@_ > 1 and not grep(ref($_), @_)) { } 101 2489 2590
Condition100%3/3
@_ == 1 and not ref $_[0]
!ll&&!rl&&r
249397105
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
2132276101
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 2489 ▶ if ( !defined $_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $_) { } 37 11800 11837
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 11800 $_;
1989 }
1990 } @_;
1991 }
1992  
1993 2695 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 2695 my $cur_kid; # references kid or handle being parsed
1999 2695 my $next_kid_close_stdin = 0;
2000  
2001 2695 my $assumed_fd = 0; # fd to assume in succinct mode (no redir ops)
2002 2695 my $handle_num = 0; # 1... is which handle we're parsing
2003  
2004 2695 my IPC::Run $self = bless {}, __PACKAGE__;
2005  
2006 2695 local $cur_self = $self;
2007  
2008 2695 $self->{ID} = ++$harness_id;
2009 2695 $self->{IOS} = [];
2010 2695 $self->{KIDS} = [];
2011 2695 $self->{PIPES} = [];
2012 2695 $self->{PTYS} = {};
2013 2695 $self->{TIMERS} = [];
2014 2695 $self->{STATE} = _newed;
2015  
2016 2695 ▶ if ($options) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options) 0 2695 2695
2017 0 $self->{$_} = $options->{$_} for keys %$options;
2018 }
2019  
2020 2695 ▶ _debug "****** harnessing *****" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 2695 2695
2021  
2022 2695 my $first_parse;
2023 2695 local $_;
2024 2695 my $arg_count = @args;
2025 2695 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 8967 2695 11662
2026 8967 for ( shift @args ) {
2027 8967 eval {
2028 8967 $first_parse = 1;
2029 8967 ▶ _debug( "parsing ", _debugstrings($_) ) if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 8967 8967
2030  
2031 REPARSE:
2032 11390 ▶ 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') { } 2634 8756 11390
elsif (UNIVERSAL::isa($_, 'IPC::Run::IO')) { } 2 8754 8756
elsif (UNIVERSAL::isa($_, 'IPC::Run::Timer')) { } 400 8354 8754
elsif (ref $_ eq 'IPC::Run::Undef') { } 35 8319 8354
elsif (/^(\d*)>&(\d+)$/) { } 74 8245 8319
elsif (/^(\d*)<&(\d+)$/) { } 34 8211 8245
elsif (/^(\d*)<&-$/) { } 43 8168 8211
elsif (/^(\d*) (<blocking_pipe)() () () $/x or /^(\d*) (<pipe)() () () $/x or /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x or /^(\d*) (<) () () (.*)$/x) { } 1403 6765 8168
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) { } 2847 3918 6765
elsif ($_ eq '|') { } 33 3885 3918
elsif ($_ eq '&') { } 44 3841 3885
elsif ($_ eq 'init') { } 89 3752 3841
elsif ($_ eq 'env') { } 10 3742 3752
elsif (not ref $_) { } 1319 2423 3742
elsif (ref $_ eq 'IPC::Run::Undef') { } 0 2423 2423
elsif ($_ eq 'init') { } 0 2423 2423
elsif ($succinct and $first_parse) { } 2423 0 2423
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
22883468756
ref $_ eq "ARRAY" or UNIVERSAL::isa($_, "IPC::Run::Win32Process")
l!l&&r!l&&!r
228809102
not $cur_kid and ref $_ eq "CODE"
!ll&&!rl&&r
73701386346
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 2634 ▶ croak "Process control symbol ('|', '&') missing" if $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
if $cur_kid 0 2634 2634
2036 2634 ▶ croak "Can't spawn a subroutine on Win32"
Branch: 1 branch
BranchTrueFalseTotal
if &Win32_MODE() and ref $_ eq "CODE" 0 2634 2634
Condition33%1/3
&Win32_MODE() and ref $_ eq "CODE"
!ll&&!rl&&r
263400
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 $cur_kid = {
2039 TYPE => 'cmd',
2040 VAL => $_,
2041 2634 NUM => @{ $self->{KIDS} } + 1,
2042 OPS => [],
2043 PID => '',
2044 RESULT => undef,
2045 };
2046  
2047 2634 ▶ unshift @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
if $next_kid_close_stdin 34 2600 2634
2048 TYPE => 'close',
2049 KFD => 0,
2050 } if $next_kid_close_stdin;
2051 2634 $next_kid_close_stdin = 0;
2052  
2053 2634 push @{ $self->{KIDS} }, $cur_kid;
2054 2634 $succinct = 1;
2055 }
2056  
2057 elsif ( UNIVERSAL::isa( $_, 'IPC::Run::IO' ) ) {
2058 2 push @{ $self->{IOS} }, $_;
2059 2 $cur_kid = undef;
2060 2 $succinct = 1;
2061 }
2062  
2063 elsif ( UNIVERSAL::isa( $_, 'IPC::Run::Timer' ) ) {
2064 400 push @{ $self->{TIMERS} }, $_;
2065 400 $succinct = 1;
2066 }
2067  
2068 elsif ( ref $_ eq 'IPC::Run::Undef' ) {
2069 ## Silently ignore undef values passed where a timer or
2070 ## other optional argument would go (e.g. undef timeout).
2071 ## See https://github.com/cpan-authors/IPC-Run/issues/128
2072 }
2073  
2074 elsif (/^(\d*)>&(\d+)$/) {
2075 74 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 10 64 74
2076 64 ▶ push @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 64 0 64
2077 TYPE => 'dup',
2078 KFD1 => $2,
2079 KFD2 => length $1 ? $1 : 1,
2080 };
2081 64 ▶ _debug "redirect operators now required" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 64 64
2082 64 $succinct = !$first_parse;
2083 }
2084  
2085 elsif (/^(\d*)<&(\d+)$/) {
2086 34 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 10 24 34
2087 24 ▶ push @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 24 0 24
2088 TYPE => 'dup',
2089 KFD1 => $2,
2090 KFD2 => length $1 ? $1 : 0,
2091 };
2092 24 $succinct = !$first_parse;
2093 }
2094  
2095 elsif (/^(\d*)<&-$/) {
2096 43 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 20 23 43
2097 23 ▶ push @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 23 0 23
2098 TYPE => 'close',
2099 KFD => length $1 ? $1 : 0,
2100 };
2101 23 $succinct = !$first_parse;
2102 }
2103  
2104 ▶ 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
11412896765
/^(\d*) (<blocking_pipe)() () () $/x or /^(\d*) (<pipe)() () () $/x or /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x
l!l&&r!l&&!r
100148054
/^(\d*) (<blocking_pipe)() () () $/x or /^(\d*) (<pipe)() () () $/x
l!l&&r!l&&!r
63378068
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
2105 || /^(\d*) (<pipe)() () () $/x
2106 || /^(\d*) (<pty) ((?:\s+\S+)?) (<) () $/x
2107 || /^(\d*) (<) () () (.*)$/x ) {
2108 1403 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 20 1383 1403
2109  
2110 1383 $succinct = !$first_parse;
2111  
2112 1383 my $type = $2 . $4;
2113  
2114 1383 ▶ my $kfd = length $1 ? $1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 995 388 1383
2115  
2116 1383 my $pty_id;
2117 1383 ▶ if ( $type eq '<pty<' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "<pty<") 14 1369 1383
2118 14 ▶ $pty_id = length $3 ? $3 : '0';
Branch: 1 branch
BranchTrueFalseTotal
length $3 ? : 0 14 14
2119 ## do the require here to cause early error reporting
2120 14 require IO::Pty;
2121 ## Just flag the pyt's existence for now. It'll be
2122 ## converted to a real IO::Pty by _open_pipes.
2123 14 $self->{PTYS}->{$pty_id} = undef;
2124 }
2125  
2126 1383 my $source = $5;
2127  
2128 1383 my @filters;
2129 1383 my $binmode = 1;
2130  
2131 1383 ▶ unless ( length $source ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $source) 1322 61 1383
2132 1322 ▶ if ( !$succinct ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($succinct) 387 935 1322
2133 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
3439522
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/DC40%2/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 table37%3/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
2134 && ( ( 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" ) ) {
2135 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
2136 42 $binmode = shift(@args)->();
2137 }
2138 else {
2139 22 push @filters, shift @args;
2140 }
2141 }
2142 }
2143 1322 $source = shift @args;
2144 1322 ▶ croak "'$_' missing a source" if _empty $source;
Branch: 1 branch
BranchTrueFalseTotal
if &_empty($source) 0 1322 1322
2145  
2146 _debug(
2147 1322 ▶ 'Kid ', $cur_kid->{NUM}, "'s input fd ", $kfd,
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() and @filters 0 1322 1322
Condition33%1/3
&_debugging_details() and @filters
!ll&&!rl&&r
132200
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
2148 ' has ', scalar(@filters), ' filters.'
2149 ) if _debugging_details && @filters;
2150 }
2151  
2152 1383 my IPC::Run::IO $pipe = IPC::Run::IO->_new_internal( $type, $kfd, $pty_id, $source, $binmode, @filters );
2153  
2154 1383 ▶ 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 1317 1383
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
12546366
ref $source eq "GLOB" || UNIVERSAL::isa($source, "IO::Handle") and not $type =~ /^<p(ty<|ipe)$/
!ll&&!rl&&r
122133129
ref $source eq "GLOB" or UNIVERSAL::isa($source, "IO::Handle")
l!l&&r!l&&!r
132301221
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
2155 && $type !~ /^<p(ty<|ipe)$/ && $type ne '<blocking_pipe' ) {
2156 ## GH#57: For plain input redirects (<) on non-standard
2157 ## fds, do NOT set DONT_CLOSE. After fork the parent no
2158 ## longer needs the input handle — the child has its own
2159 ## copy via dup2. Keeping it open prevents EPIPE/SIGPIPE
2160 ## when the child exits early, which can hang the writer.
2161 ## Protect stdin/stdout/stderr (fd 0-2) since closing
2162 ## those in the parent would be destructive.
2163 66 my $fno = fileno $source;
2164 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
2165 0 ▶ _debug "setting DONT_CLOSE for std fd" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
2166 0 $pipe->{DONT_CLOSE} = 1;
2167 }
2168 66 ▶ _dont_inherit($source) if Win32_MODE;
Branch: 1 branch
BranchTrueFalseTotal
if &Win32_MODE() 0 66 66
2169 }
2170  
2171 1383 push @{ $cur_kid->{OPS} }, $pipe;
2172 }
2173  
2174 ▶ 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
12227253918
/^() (>>?) (&) () (.*)$/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
12026643
/^() (>>?) (&) () (.*)$/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
93276645
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x or /^() (&) (>pty) ( \w*)> () $/x
l!l&&r!l&&!r
9306672
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x or /^(\d*)() (>pipe) () () $/x
l!l&&r!l&&!r
31626672
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x or /^() (>pipe)(&) () () $/x
l!l&&r!l&&!r
3106734
/^() (>>?) (&) () (.*)$/x or /^() (&) (>pipe) () () $/x
l!l&&r!l&&!r
3106734
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
2175 /^() (>>?) (&) () (.*)$/x
2176 || /^() (&) (>pipe) () () $/x
2177 || /^() (>pipe)(&) () () $/x
2178 || /^(\d*)() (>pipe) () () $/x
2179 || /^() (&) (>pty) ( \w*)> () $/x
2180 ## TODO: || /^() (>pty) (\d*)> (&) () $/x
2181 || /^(\d*)() (>pty) ( \w*)> () $/x
2182 || /^() (&) (>>?) () (.*)$/x || /^(\d*)() (>>?) () (.*)$/x
2183 ) {
2184 2847 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 30 2817 2847
2185  
2186 2817 $succinct = !$first_parse;
2187  
2188 2817 ▶ my $type = (
Branch: 2 branches
BranchTrueFalseTotal
$2 eq '>pipe' || $3 eq '>pipe' ? : 62 2755 2817
$2 eq '>pty' || $3 eq '>pty' ? : 27 2728 2755
Condition66%4/6
$2 eq ">pipe" or $3 eq ">pipe"
l!l&&r!l&&!r
0622755
$2 eq ">pty" or $3 eq ">pty"
l!l&&r!l&&!r
0272728
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
2189 $2 eq '>pipe' || $3 eq '>pipe' ? '>pipe'
2190 : $2 eq '>pty' || $3 eq '>pty' ? '>pty>'
2191 : '>'
2192 );
2193 2817 ▶ my $kfd = length $1 ? $1 : 1;
Branch: 1 branch
BranchTrueFalseTotal
length $1 ? : 1905 912 2817
2194 2817 ▶ my $trunc = !( $2 eq '>>' || $3 eq '>>' );
Condition66%2/3
$2 eq '>>' || $3 eq '>>'
l!l&&r!l&&!r
0442773
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
2195 2817 ▶ my $pty_id = (
Branch: 2 branches
BranchTrueFalseTotal
$2 eq '>pty' || $3 eq '>pty' ? : 27 2790 2817
length $4 ? : 0 27 27
Condition66%2/3
$2 eq ">pty" or $3 eq ">pty"
l!l&&r!l&&!r
0272790
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
2196 $2 eq '>pty' || $3 eq '>pty'
2197 ? length $4
2198 ? $4
2199 : 0
2200 : undef
2201 );
2202  
2203 2817 ▶ my $stderr_too =
Condition100%9/9
$2 eq '&' || $3 eq '&' || !length($1) && substr($type, 0, 4) eq '>pty'
l!l&&r!l&&!r
23272767
$2 eq "&" or $3 eq "&"
l!l&&r!l&&!r
2212794
not length $1 and substr($type, 0, 4) eq ">pty"
!ll&&!rl&&r
190586227
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
2204 $2 eq '&'
2205 || $3 eq '&'
2206 || ( !length $1 && substr( $type, 0, 4 ) eq '>pty' );
2207  
2208 2817 my $dest = $5;
2209 2817 my @filters;
2210 2817 my $binmode = 1;
2211 2817 ▶ unless ( length $dest ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $dest) 2620 197 2817
2212 2620 ▶ if ( !$succinct ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($succinct) 1132 1488 2620
2213 ## unshift...shift: '>' filters source...sink left...right
2214 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
72446122
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/DC40%2/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 table62%5/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
2215 && ( ( 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" ) ) {
2216 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
2217 49 $binmode = shift(@args)->();
2218 }
2219 else {
2220 26 unshift @filters, shift @args;
2221 }
2222 }
2223 }
2224  
2225 2620 ▶ if ( @args && ref $args[0] eq 'IPC::Run::Undef' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args and ref $args[0] eq 'IPC::Run::Undef') { } 2 2618 2620
Condition66%2/3
@args and ref $args[0] eq "IPC::Run::Undef"
!ll&&!rl&&r
026182
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
2226 2 require Symbol;
2227 2 ${ $args[0] } = $dest = Symbol::gensym();
2228 2 shift @args;
2229 }
2230 else {
2231 2618 $dest = shift @args;
2232 }
2233  
2234 _debug(
2235 2620 ▶ 'Kid ', $cur_kid->{NUM}, "'s output fd ", $kfd,
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() and @filters 0 2620 2620
Condition33%1/3
&_debugging_details() and @filters
!ll&&!rl&&r
262000
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
2236 ' has ', scalar(@filters), ' filters.'
2237 ) if _debugging_details && @filters;
2238  
2239 2620 ▶ if ( $type eq '>pty>' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq ">pty>") 27 2593 2620
2240 ## do the require here to cause early error reporting
2241 27 require IO::Pty;
2242 ## Just flag the pyt's existence for now. _open_pipes()
2243 ## will new an IO::Pty for each key.
2244 27 $self->{PTYS}->{$pty_id} = undef;
2245 }
2246 }
2247  
2248 2817 ▶ croak "'$_' missing a destination" if _empty $dest;
Branch: 1 branch
BranchTrueFalseTotal
if &_empty($dest) 0 2817 2817
2249 2817 my $pipe = IPC::Run::IO->_new_internal( $type, $kfd, $pty_id, $dest, $binmode, @filters );
2250 2817 $pipe->{TRUNC} = $trunc;
2251  
2252 2817 ▶ 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 2757 2817
Condition83%5/6
UNIVERSAL::isa($dest, "GLOB") || UNIVERSAL::isa($dest, "IO::Handle") and not $type =~ /^>(pty>|pipe)$/
!ll&&!rl&&r
26995860
UNIVERSAL::isa($dest, "GLOB") or UNIVERSAL::isa($dest, "IO::Handle")
l!l&&r!l&&!r
11802699
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
2253 && $type !~ /^>(pty>|pipe)$/ ) {
2254 60 ▶ _debug "setting DONT_CLOSE" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 60 60
2255 60 $pipe->{DONT_CLOSE} = 1; ## this FD is not closed by us.
2256 }
2257 2817 push @{ $cur_kid->{OPS} }, $pipe;
2258 2817 ▶ push @{ $cur_kid->{OPS} }, {
Branch: 1 branch
BranchTrueFalseTotal
if $stderr_too 50 2767 2817
2259 TYPE => 'dup',
2260 KFD1 => 1,
2261 KFD2 => 2,
2262 } if $stderr_too;
2263 }
2264  
2265 elsif ( $_ eq "|" ) {
2266 33 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 10 23 33
2267 23 unshift @{ $cur_kid->{OPS} }, {
2268 TYPE => '|',
2269 KFD => 1,
2270 };
2271 23 $succinct = 1;
2272 23 $assumed_fd = 1;
2273 23 $cur_kid = undef;
2274 }
2275  
2276 elsif ( $_ eq "&" ) {
2277 44 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 10 34 44
2278 34 $next_kid_close_stdin = 1;
2279 34 $succinct = 1;
2280 34 $assumed_fd = 0;
2281 34 $cur_kid = undef;
2282 }
2283  
2284 elsif ( $_ eq 'init' ) {
2285 89 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 0 89 89
2286 89 push @{ $cur_kid->{OPS} }, {
2287 TYPE => 'init',
2288 SUB => shift @args,
2289 };
2290 }
2291  
2292 elsif ( $_ eq 'env' ) {
2293 10 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 0 10 10
2294 10 my $env = shift @args;
2295 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
2296 9 $cur_kid->{ENV} = $env;
2297 }
2298  
2299 elsif ( !ref $_ ) {
2300 1319 $self->{$_} = shift @args;
2301 }
2302  
2303 elsif ( ref $_ eq 'IPC::Run::Undef' ) {
2304 ## bare undef argument - silently ignore to preserve
2305 ## pre-20180523.0 behavior where undef matched !ref $_ and
2306 ## was absorbed as a no-op. See GH#124.
2307 }
2308  
2309 elsif ( $_ eq 'init' ) {
2310 0 ▶ croak "No command before '$_'" unless $cur_kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_kid 0 0 0
2311 0 push @{ $cur_kid->{OPS} }, {
2312 TYPE => 'init',
2313 SUB => shift @args,
2314 };
2315 }
2316  
2317 ▶ elsif ( $succinct && $first_parse ) {
Condition33%1/3
$succinct and $first_parse
!ll&&!rl&&r
002423
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
2318 ## It's not an opcode, and no explicit opcodes have been
2319 ## seen yet, so assume it's a file name.
2320 2423 unshift @args, $_;
2321 2423 ▶ if ( !$assumed_fd ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $assumed_fd) { } 935 1488 2423
2322 935 $_ = "$assumed_fd<",
2323 }
2324 else {
2325 1488 $_ = "$assumed_fd>",
2326 }
2327 2423 ▶ _debug "assuming '", $_, "'" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2423 2423
2328 2423 ++$assumed_fd;
2329 2423 $first_parse = 0;
2330 2423 goto REPARSE;
2331 }
2332  
2333 else {
2334 0 ▶ croak join(
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 0 0
2335 '',
2336 'Unexpected ',
2337 ( ref() ? $_ : 'scalar' ),
2338 ' in harness() parameter ',
2339 $arg_count - @args
2340 );
2341 }
2342 };
2343 8967 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 111 8856 8967
2344 111 push @errs, $@;
2345 111 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 111 111
2346 }
2347 }
2348 }
2349  
2350 2695 ▶ die join( '', @errs ) if @errs;
Branch: 1 branch
BranchTrueFalseTotal
if @errs 111 2584 2695
2351  
2352 2584 $self->{STATE} = _harnessed;
2353  
2354 # $self->timeout( $options->{timeout} ) if exists $options->{timeout};
2355 2584 return $self;
2356 }
2357  
2358 sub _open_pipes {
2359 2431 ▶ my IPC::Run $self = shift;
Subroutine _open_pipes: called CC=86 SCAR=49.9
2360  
2361 2431 my @errs;
2362  
2363 my @close_on_fail;
2364  
2365 ## When a pipe character is seen, a pipe is created. $pipe_read_fd holds
2366 ## the dangling read end of the pipe until we get to the next process.
2367 2431 my $pipe_read_fd;
2368  
2369 ## Output descriptors for the last command are shared by all children.
2370 ## @output_fds_accum accumulates the current set of output fds.
2371 2431 my @output_fds_accum;
2372  
2373 2431 for ( sort keys %{ $self->{PTYS} } ) {
2374 36 ▶ _debug "opening pty '", $_, "'" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 36 36
2375 36 eval {
2376 36 my $pty = _pty;
2377 35 $self->{PTYS}->{$_} = $pty;
2378 };
2379 36 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 35 36
2380 1 push @errs, $@;
2381 1 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 1 1
2382 }
2383 }
2384  
2385 2431 for ( @{ $self->{IOS} } ) {
2386 2 eval { $_->init; };
2387 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 2 2
2388 0 push @errs, $@;
2389 0 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
2390 }
2391 else {
2392 2 push @close_on_fail, $_;
2393 }
2394 }
2395  
2396 ## Loop through the kids and their OPS, interpreting any that require
2397 ## parent-side actions.
2398 2431 for my $kid ( @{ $self->{KIDS} } ) {
2399 2486 ▶ if ( ref $kid->{VAL} eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $kid->{"VAL"} eq "ARRAY") 2140 346 2486
2400 2140 $kid->{PATH} = _search_path $kid->{VAL}->[0];
2401 }
2402 2482 ▶ if ( defined $pipe_read_fd ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pipe_read_fd) 23 2459 2482
2403 23 ▶ _debug "placing write end of pipe on kid $kid->{NUM}'s stdin"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 23 23
2404 if _debugging_details;
2405 23 unshift @{ $kid->{OPS} }, {
2406 TYPE => 'PIPE', ## Prevent next loop from triggering on this
2407 KFD => 0,
2408 TFD => $pipe_read_fd,
2409 };
2410 23 $pipe_read_fd = undef;
2411 }
2412 2482 @output_fds_accum = ();
2413 2482 for my $op ( @{ $kid->{OPS} } ) {
2414  
2415 # next if $op->{IS_DEBUG};
2416 4505 my $ok = eval {
2417 4505 ▶ if ( $op->{TYPE} eq '<' ) {
Branch: 8 branches
BranchTrueFalseTotal
if ($op->{'TYPE'} eq '<') { } 1257 3248 4505
elsif ($op->{'TYPE'} eq '<pipe' or $op->{'TYPE'} eq '<blocking_pipe') { } 98 3150 3248
elsif ($op->{'TYPE'} eq '<pty<') { } 14 3136 3150
elsif ($op->{'TYPE'} eq '>') { } 2723 413 3136
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
2418 1257 my $source = $op->{SOURCE};
2419 1257 ▶ if ( !ref $source ) {
Branch: 4 branches
BranchTrueFalseTotal
if (not ref $source) { } 83 1174 1257
elsif (UNIVERSAL::isa($source, 'GLOB') or UNIVERSAL::isa($source, 'IO::Handle')) { } 66 1108 1174
elsif (UNIVERSAL::isa($source, 'SCALAR')) { } 1027 81 1108
elsif (UNIVERSAL::isa($source, 'CODE')) { } 71 10 81
2420 _debug(
2421 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2422 83 ▶ " from '" . $source, "' (read only)"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 83 83
2423 ) if _debugging_details;
2424 croak "simulated open failure"
2425 83 ▶ if $self->{_simulate_open_failure};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_simulate_open_failure"} 10 73 83
2426 73 $op->{TFD} = _sysopen( $source, O_RDONLY );
2427 51 push @close_on_fail, $op->{TFD};
2428 }
2429 ▶ elsif (UNIVERSAL::isa( $source, 'GLOB' )
Condition100%3/3
UNIVERSAL::isa($source, "GLOB") or UNIVERSAL::isa($source, "IO::Handle")
l!l&&r!l&&!r
36301108
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
2430 || UNIVERSAL::isa( $source, 'IO::Handle' ) ) {
2431 66 ▶ croak "Unopened filehandle in input redirect for $op->{KFD}"
Branch: 1 branch
BranchTrueFalseTotal
unless defined fileno $source 0 66 66
2432 unless defined fileno $source;
2433 66 $op->{TFD} = fileno $source;
2434 _debug(
2435 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2436 " from fd ", $op->{TFD}
2437 66 ▶ ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 66 66
2438 }
2439 elsif ( UNIVERSAL::isa( $source, 'SCALAR' ) ) {
2440 _debug(
2441 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2442 1027 ▶ " from SCALAR"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1027 1027
2443 ) if _debugging_details;
2444  
2445 1027 $op->open_pipe( $self->_debug_fd );
2446 1027 push @close_on_fail, $op->{KFD}, $op->{FD};
2447  
2448 1027 my $s = '';
2449 1027 $op->{KIN_REF} = \$s;
2450 }
2451 elsif ( UNIVERSAL::isa( $source, 'CODE' ) ) {
2452 71 ▶ _debug( 'kid ', $kid->{NUM}, ' to read ', $op->{KFD}, ' from CODE' ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 71 71
2453  
2454 71 $op->open_pipe( $self->_debug_fd );
2455 71 push @close_on_fail, $op->{KFD}, $op->{FD};
2456  
2457 71 my $s = '';
2458 71 $op->{KIN_REF} = \$s;
2459 }
2460 else {
2461 10 croak( "'" . ref($source) . "' not allowed as a source for input redirection" );
2462 }
2463 1215 $op->_init_filters;
2464 }
2465 ▶ 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
35633150
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
2466 _debug(
2467 'kid to read ', $op->{KFD},
2468 98 ▶ ' from a pipe IPC::Run opens and returns',
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 98 98
2469 ) if _debugging_details;
2470  
2471 98 my ( $r, $w ) = $op->open_pipe( $self->_debug_fd, $op->{SOURCE} );
2472 0 _debug "caller will write to ", fileno( ref $op->{SOURCE} eq 'SCALAR' ? ${ $op->{SOURCE} } : $op->{SOURCE} )
2473 98 ▶ if _debugging_details;
Branch: 2 branches
BranchTrueFalseTotal
if &_debugging_details() 0 98 98
ref $op->{'SOURCE'} eq 'SCALAR' ? : 0 0 0
2474  
2475 98 $op->{TFD} = $r;
2476 98 $op->{FD} = undef; # we don't manage this fd
2477 98 $op->_init_filters;
2478 }
2479 elsif ( $op->{TYPE} eq '<pty<' ) {
2480 _debug(
2481 14 ▶ 'kid to read ', $op->{KFD}, " from pty '", $op->{PTY_ID}, "'",
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 14 14
2482 ) if _debugging_details;
2483  
2484 14 for my $source ( $op->{SOURCE} ) {
2485 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
2486 _debug(
2487 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2488 14 ▶ " from SCALAR via pty '", $op->{PTY_ID}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 14 14
2489 ) if _debugging_details;
2490  
2491 14 my $s = '';
2492 14 $op->{KIN_REF} = \$s;
2493 }
2494 elsif ( UNIVERSAL::isa( $source, 'CODE' ) ) {
2495 _debug(
2496 "kid ", $kid->{NUM}, " to read ", $op->{KFD},
2497 0 ▶ " from CODE via pty '", $op->{PTY_ID}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
2498 ) if _debugging_details;
2499 0 my $s = '';
2500 0 $op->{KIN_REF} = \$s;
2501 }
2502 else {
2503 0 croak( "'" . ref($source) . "' not allowed as a source for '<pty<' redirection" );
2504 }
2505 }
2506 14 $op->{FD} = $self->{PTYS}->{ $op->{PTY_ID} }->fileno;
2507 13 $op->{TFD} = undef; # The fd isn't known until after fork().
2508 13 $op->_init_filters;
2509 }
2510 elsif ( $op->{TYPE} eq '>' ) {
2511 ## N> output redirection.
2512 2723 my $dest = $op->{DEST};
2513 2723 ▶ if ( !ref $dest ) {
Branch: 4 branches
BranchTrueFalseTotal
if (not ref $dest) { } 201 2522 2723
elsif (UNIVERSAL::isa($dest, 'GLOB')) { } 60 2462 2522
elsif (UNIVERSAL::isa($dest, 'SCALAR')) { } 2336 126 2462
elsif (UNIVERSAL::isa($dest, 'CODE')) { } 116 10 126
2514 _debug(
2515 "kid ", $kid->{NUM}, " to write ", $op->{KFD},
2516 " to '", $dest, "' (write only, create, ",
2517 201 ▶ ( $op->{TRUNC} ? 'truncate' : 'append' ),
Branch: 2 branches
BranchTrueFalseTotal
if &_debugging_details() 0 201 201
$op->{'TRUNC'} ? : 0 0 0
2518 ")"
2519 ) if _debugging_details;
2520 croak "simulated open failure"
2521 201 ▶ if $self->{_simulate_open_failure};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_simulate_open_failure"} 10 191 201
2522 $op->{TFD} = _sysopen(
2523 $dest,
2524 191 ▶ ( O_WRONLY | O_CREAT | ( $op->{TRUNC} ? O_TRUNC : O_APPEND ) )
Branch: 1 branch
BranchTrueFalseTotal
$op->{'TRUNC'} ? : 151 40 191
2525 );
2526 191 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) 0 191 191
2527 ## I have no idea why this is needed to make the current
2528 ## file position survive the gyrations TFD must go
2529 ## through...
2530 0 POSIX::lseek( $op->{TFD}, 0, POSIX::SEEK_END() );
2531 }
2532 191 push @close_on_fail, $op->{TFD};
2533 }
2534 elsif ( UNIVERSAL::isa( $dest, 'GLOB' ) ) {
2535 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
2536 ## Turn on autoflush, mostly just to flush out
2537 ## existing output.
2538 60 my $old_fh = select($dest);
2539 60 $| = 1;
2540 60 select($old_fh);
2541 60 $op->{TFD} = fileno $dest;
2542 60 ▶ _debug( 'kid to write ', $op->{KFD}, ' to handle ', $op->{TFD} ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 60 60
2543 }
2544 elsif ( UNIVERSAL::isa( $dest, 'SCALAR' ) ) {
2545 2336 ▶ _debug( "kid ", $kid->{NUM}, " to write $op->{KFD} to SCALAR" ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2336 2336
2546  
2547 2336 $op->open_pipe( $self->_debug_fd );
2548 2336 push @close_on_fail, $op->{FD}, $op->{TFD};
2549 2336 ▶ $$dest = '' if $op->{TRUNC};
Branch: 1 branch
BranchTrueFalseTotal
if $op->{"TRUNC"} 2336 0 2336
2550 }
2551 elsif ( UNIVERSAL::isa( $dest, 'CODE' ) ) {
2552 116 ▶ _debug("kid $kid->{NUM} to write $op->{KFD} to CODE") if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 116 116
2553  
2554 116 $op->open_pipe( $self->_debug_fd );
2555 116 push @close_on_fail, $op->{FD}, $op->{TFD};
2556 }
2557 else {
2558 10 croak( "'" . ref($dest) . "' not allowed as a sink for output redirection" );
2559 }
2560 2703 $output_fds_accum[ $op->{KFD} ] = $op;
2561 2703 $op->_init_filters;
2562 }
2563  
2564 elsif ( $op->{TYPE} eq '>pipe' ) {
2565 ## N> output redirection to a pipe we open, but don't select()
2566 ## on.
2567 _debug(
2568 "kid ", $kid->{NUM}, " to write ", $op->{KFD},
2569 61 ▶ ' to a pipe IPC::Run opens and returns'
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 61 61
2570 ) if _debugging_details;
2571  
2572 61 my ( $r, $w ) = $op->open_pipe( $self->_debug_fd, $op->{DEST} );
2573 0 _debug "caller will read from ", fileno( ref $op->{DEST} eq 'SCALAR' ? ${ $op->{DEST} } : $op->{DEST} )
2574 61 ▶ if _debugging_details;
Branch: 2 branches
BranchTrueFalseTotal
if &_debugging_details() 0 61 61
ref $op->{'DEST'} eq 'SCALAR' ? : 0 0 0
2575  
2576 61 $op->{TFD} = $w;
2577 61 $op->{FD} = undef; # we don't manage this fd
2578 61 $op->_init_filters;
2579  
2580 61 $output_fds_accum[ $op->{KFD} ] = $op;
2581 }
2582 elsif ( $op->{TYPE} eq '>pty>' ) {
2583 27 my $dest = $op->{DEST};
2584 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
2585 _debug(
2586 "kid ", $kid->{NUM}, " to write ", $op->{KFD},
2587 27 ▶ " to SCALAR via pty '", $op->{PTY_ID}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 27 27
2588 ) if _debugging_details;
2589  
2590 27 ▶ $$dest = '' if $op->{TRUNC};
Branch: 1 branch
BranchTrueFalseTotal
if $op->{"TRUNC"} 27 0 27
2591 }
2592 elsif ( UNIVERSAL::isa( $dest, 'CODE' ) ) {
2593 _debug(
2594 "kid ", $kid->{NUM}, " to write ", $op->{KFD},
2595 0 ▶ " to CODE via pty '", $op->{PTY_ID}, "'"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
2596 ) if _debugging_details;
2597 }
2598 else {
2599 0 croak( "'" . ref($dest) . "' not allowed as a sink for output redirection" );
2600 }
2601  
2602 27 $op->{FD} = $self->{PTYS}->{ $op->{PTY_ID} }->fileno;
2603 27 $op->{TFD} = undef; # The fd isn't known until after fork().
2604 27 $output_fds_accum[ $op->{KFD} ] = $op;
2605 27 $op->_init_filters;
2606 }
2607 elsif ( $op->{TYPE} eq '|' ) {
2608 23 ▶ _debug( "pipelining $kid->{NUM} and " . ( $kid->{NUM} + 1 ) ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 23 23
2609 23 ( $pipe_read_fd, $op->{TFD} ) = _pipe;
2610 23 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) 0 23 23
2611 0 _dont_inherit($pipe_read_fd);
2612 0 _dont_inherit( $op->{TFD} );
2613 }
2614 23 @output_fds_accum = ();
2615 }
2616 elsif ( $op->{TYPE} eq '&' ) {
2617 0 @output_fds_accum = ();
2618 } # end if $op->{TYPE} tree
2619 4442 1;
2620 }; # end eval
2621 4505 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 63 4442 4505
2622 63 push @errs, $@;
2623 63 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 63 63
2624 }
2625 } # end for ( OPS }
2626 }
2627  
2628 2427 ▶ if (@errs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@errs) 63 2364 2427
2629 63 for (@close_on_fail) {
2630 26 _close($_);
2631 26 $_ = undef;
2632 }
2633 63 for ( keys %{ $self->{PTYS} } ) {
2634 1 ▶ next unless $self->{PTYS}->{$_};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"PTYS"}{$_} 1 0 1
2635 0 close $self->{PTYS}->{$_};
2636 0 $self->{PTYS}->{$_} = undef;
2637 }
2638 63 die join( '', @errs );
2639 }
2640  
2641 ## give all but the last child all of the output file descriptors
2642 ## These will be reopened (and thus rendered useless) if the child
2643 ## dup2s on to these descriptors, since we unshift these. This way
2644 ## each process emits output to the same file descriptors that the
2645 ## last child will write to. This is probably not quite correct,
2646 ## since each child should write to the file descriptors inherited
2647 ## from the parent.
2648 ## TODO: fix the inheritance of output file descriptors.
2649 ## NOTE: This sharing of OPS among kids means that we can't easily put
2650 ## a kid number in each OPS structure to ping the kid when all ops
2651 ## have closed (when $self->{PIPES} has emptied). This means that we
2652 ## need to scan the KIDS whenever @{$self->{PIPES}} is empty to see
2653 ## if there any of them are still alive.
2654 2364 ▶ for ( my $num = 0; $num < $#{ $self->{KIDS} }; ++$num ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num < $#{$$self{"KIDS"};}) 57 2364 2421
2655 57 for ( reverse @output_fds_accum ) {
2656 86 ▶ next unless defined $_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 30 56 86
2657 _debug(
2658 'kid ', $self->{KIDS}->[$num]->{NUM}, ' also to write ', $_->{KFD},
2659 ' to ', ref $_->{DEST}
2660 56 ▶ ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 56 56
2661 56 unshift @{ $self->{KIDS}->[$num]->{OPS} }, $_;
2662 }
2663 }
2664  
2665 ## Open the debug pipe if we need it
2666 ## Create the list of PIPES we need to scan and the bit vectors needed by
2667 ## select(). Do this first so that _cleanup can _clobber() them if an
2668 ## exception occurs.
2669 2364 @{ $self->{PIPES} } = ();
2670 2364 $self->{RIN} = '';
2671 2364 $self->{WIN} = '';
2672 2364 $self->{EIN} = '';
2673 ## PIN is a vec()tor that indicates who's paused.
2674 2364 $self->{PIN} = '';
2675 2364 for my $kid ( @{ $self->{KIDS} } ) {
2676 2419 for ( @{ $kid->{OPS} } ) {
2677 4474 ▶ if ( defined $_->{FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_->{"FD"}) 3644 830 4474
2678 _debug(
2679 'kid ', $kid->{NUM}, '[', $kid->{PID}, "]'s ", $_->{KFD},
2680 ' is my ', $_->{FD}
2681 3644 ▶ ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 3644 3644
2682 3644 ▶ vec( $self->{ $_->{TYPE} =~ /^</ ? 'WIN' : 'RIN' }, $_->{FD}, 1 ) = 1;
Branch: 1 branch
BranchTrueFalseTotal
$_->{'TYPE'} =~ /^</ ? : 1111 2533 3644
2683  
2684 # vec( $self->{EIN}, $_->{FD}, 1 ) = 1;
2685 3644 push @{ $self->{PIPES} }, $_;
2686 }
2687 }
2688 }
2689  
2690 2364 for my $io ( @{ $self->{IOS} } ) {
2691 2 my $fd = $io->fileno;
2692 2 ▶ vec( $self->{RIN}, $fd, 1 ) = 1 if $io->mode =~ /r/;
Branch: 1 branch
BranchTrueFalseTotal
if $io->mode =~ /r/ 1 1 2
2693 2 ▶ vec( $self->{WIN}, $fd, 1 ) = 1 if $io->mode =~ /w/;
Branch: 1 branch
BranchTrueFalseTotal
if $io->mode =~ /w/ 1 1 2
2694  
2695 # vec( $self->{EIN}, $fd, 1 ) = 1;
2696 2 push @{ $self->{PIPES} }, $io;
2697 }
2698  
2699 ## Put filters on the end of the filter chains to read & write the pipes.
2700 ## Clear pipe states
2701 2364 for my $pipe ( @{ $self->{PIPES} } ) {
2702 3646 $pipe->{SOURCE_EMPTY} = 0;
2703 3646 $pipe->{PAUSED} = 0;
2704 3646 ▶ if ( $pipe->{TYPE} =~ /^>/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pipe->{'TYPE'} =~ /^>/) { } 2534 1112 3646
2705 my $pipe_reader = sub {
2706 4182 ▶ my ( undef, $out_ref ) = @_;
Subroutine __ANON__: called CC=11 SCAR=27.6
2707  
2708 4182 ▶ return undef unless defined $pipe->{FD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pipe->{"FD"} 0 4182 4182
2709 4182 ▶ return 0 unless vec( $self->{ROUT}, $pipe->{FD}, 1 );
Branch: 1 branch
BranchTrueFalseTotal
unless vec $self->{"ROUT"}, $pipe->{"FD"}, 1 0 4182 4182
2710  
2711 4182 vec( $self->{ROUT}, $pipe->{FD}, 1 ) = 0;
2712  
2713 4182 ▶ _debug_desc_fd( 'reading from', $pipe ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 4182 4182
2714 4182 my $in = eval { _read( $pipe->{FD} ) };
2715 4182 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 21 4161 4182
2716 21 $in = '';
2717 ## IO::Pty throws the Input/output error if the kid dies.
2718 ## read() throws the bad file descriptor message if the
2719 ## kid dies on Win32.
2720 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
2721 unless $@ =~ $_EIO
2722 || ( $@ =~ /input or output/ && $^O =~ /aix/ )
2723 || ( Win32_MODE && $@ =~ /Bad file descriptor/ );
2724 }
2725  
2726 4182 ▶ unless ( length $in ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $in) 2239 1943 4182
2727 2239 $self->_clobber($pipe);
2728 2239 return undef;
2729 }
2730  
2731 ## Protect the position so /.../g matches may be used.
2732 1943 my $pos = pos $$out_ref;
2733 1943 $$out_ref .= $in;
2734 1943 pos($$out_ref) = $pos;
2735 1943 return 1;
2736 2534 };
2737 ## Input filters are the last filters
2738 2534 push @{ $pipe->{FILTERS} }, $pipe_reader;
2739 2534 push @{ $self->{TEMP_FILTERS} }, $pipe_reader;
2740 }
2741 else {
2742 my $pipe_writer = sub {
2743 3270 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=14 SCAR=26.7
2744 3270 ▶ return undef unless defined $pipe->{FD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pipe->{"FD"} 0 3270 3270
2745 return 0
2746 unless vec( $self->{WOUT}, $pipe->{FD}, 1 )
2747 3270 ▶ || $pipe->{PAUSED};
Branch: 1 branch
BranchTrueFalseTotal
unless vec $self->{"WOUT"}, $pipe->{"FD"}, 1 or $pipe->{"PAUSED"} 0 3270 3270
Condition66%2/3
vec $self->{"WOUT"}, $pipe->{"FD"}, 1 or $pipe->{"PAUSED"}
l!l&&r!l&&!r
152817420
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
2748  
2749 3270 vec( $self->{WOUT}, $pipe->{FD}, 1 ) = 0;
2750  
2751 3270 ▶ if ( !length $$in_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $$in_ref) 3256 14 3270
2752 3256 ▶ if ( !defined get_more_input ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined &get_more_input()) 697 2559 3256
2753 697 $self->_clobber($pipe);
2754 697 return undef;
2755 }
2756 }
2757  
2758 2573 ▶ unless ( length $$in_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $$in_ref) 1669 904 2573
2759 1669 ▶ unless ( $pipe->{PAUSED} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pipe->{"PAUSED"}) 89 1580 1669
2760 89 ▶ _debug_desc_fd( 'pausing', $pipe ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 89 89
2761 89 vec( $self->{WIN}, $pipe->{FD}, 1 ) = 0;
2762  
2763 # vec( $self->{EIN}, $pipe->{FD}, 1 ) = 0;
2764 89 vec( $self->{PIN}, $pipe->{FD}, 1 ) = 1;
2765 89 $pipe->{PAUSED} = 1;
2766 }
2767 1669 return 0;
2768 }
2769 904 ▶ _debug_desc_fd( 'writing to', $pipe ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 904 904
2770  
2771 904 ▶ if ( length $$in_ref && $$in_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $$in_ref and $$in_ref) { } 898 6 904
Condition66%2/3
length $$in_ref and $$in_ref
!ll&&!rl&&r
06898
MC/DC50%1/2
length $$in_ref and $$in_ref
length $$in_ref $$in_ref
Truth table66%2/3
A and B
A= length $$in_refB= $$in_ref
ABresult
0X0
100
111
2772 898 my $c = _write( $pipe->{FD}, $$in_ref );
2773 898 ▶ unless ( defined $c ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $c) 231 667 898
2774 ## EPIPE: child closed stdin before reading all input.
2775 ## Treat this exactly like EOF on the pipe.
2776 231 ▶ _debug_desc_fd( 'broken pipe writing to', $pipe )
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 231 231
2777 if _debugging_details;
2778 231 $self->_clobber($pipe);
2779 231 return undef;
2780 }
2781 667 substr( $$in_ref, 0, $c, '' );
2782 }
2783 else {
2784 6 $self->_clobber($pipe);
2785 6 return undef;
2786 }
2787  
2788 667 return 1;
2789 1112 };
2790 ## Output filters are the first filters
2791 1112 unshift @{ $pipe->{FILTERS} }, $pipe_writer;
2792 1112 push @{ $self->{TEMP_FILTERS} }, $pipe_writer;
2793 }
2794 }
2795 }
2796  
2797 sub _dup2_gently {
2798 ## A METHOD, NOT A FUNCTION, NEEDS $self!
2799 361 ▶ my IPC::Run $self = shift;
Subroutine _dup2_gently: called CC=6 SCAR=19.1
2800 361 my ( $files, $fd1, $fd2 ) = @_;
2801 ## Moves TFDs that are using the destination fd out of the
2802 ## way before calling _dup2
2803 361 for (@$files) {
2804 962 ▶ next unless defined $_->{TFD};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_->{"TFD"} 51 911 962
2805 911 ▶ $_->{TFD} = _dup( $_->{TFD} ) if $_->{TFD} == $fd2;
Branch: 1 branch
BranchTrueFalseTotal
if $_->{"TFD"} == $fd2 2 909 911
2806 }
2807 361 ▶ if ( defined $self->{DEBUG_FD} && $self->{DEBUG_FD} == $fd2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"DEBUG_FD"} and $self->{"DEBUG_FD"} == $fd2) 0 361 361
Condition33%1/3
defined $self->{"DEBUG_FD"} and $self->{"DEBUG_FD"} == $fd2
!ll&&!rl&&r
36100
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
2808 0 $self->{DEBUG_FD} = _dup $self->{DEBUG_FD};
2809 0 $fds{$self->{DEBUG_FD}}{needed} = 1;
2810 }
2811 361 _dup2_rudely( $fd1, $fd2 );
2812 }
2813  
2814 =pod
2815  
2816 =item close_terminal
2817  
2818 This is used as (or in) an init sub to cast off the bonds of a controlling
2819 terminal. It must precede all other redirection ops that affect
2820 STDIN, STDOUT, or STDERR to be guaranteed effective.
2821  
2822 =cut
2823  
2824 sub close_terminal {
2825 ## Cast of the bonds of a controlling terminal
2826  
2827 # Just in case the parent (I'm talking to you FCGI) had these tied.
2828 7 ▶ untie *STDIN;
Subroutine close_terminal: called CC=3 SCAR=11.1
Pod documented
2829 7 untie *STDOUT;
2830 7 untie *STDERR;
2831  
2832 7 ▶ POSIX::setsid() || croak "POSIX::setsid() failed";
Branch: 1 branch
BranchTrueFalseTotal
POSIX::setsid() or croak("POSIX::setsid() failed") 0 7 7
2833 7 ▶ _debug "closing stdin, out, err"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 7 7
2834 if _debugging_details;
2835 7 close STDIN;
2836 7 close STDERR;
2837 7 close STDOUT;
2838 }
2839  
2840 sub _do_kid_and_exit {
2841 184 ▶ my IPC::Run $self = shift;
Subroutine _do_kid_and_exit: called CC=42 SCAR=44.9
2842 184 my ($kid) = @_;
2843  
2844 184 my ( $s1, $s2 );
2845 184 ▶ if ( $] < 5.008 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.008") 0 184 184
2846 ## For unknown reasons, placing these two statements in the eval{}
2847 ## causes the eval {} to not catch errors after they are executed in
2848 ## perl 5.6.0, godforsaken version that it is...not sure about 5.6.1.
2849 ## Part of this could be that these symbols get destructed when
2850 ## exiting the eval, and that destruction might be what's (wrongly)
2851 ## confusing the eval{}, allowing the exception to propagate.
2852 0 $s1 = Symbol::gensym();
2853 0 $s2 = Symbol::gensym();
2854 }
2855  
2856 184 eval {
2857 184 local $cur_self = $self;
2858  
2859 ## Suppress "Filehandle STDIN reopened as ... only for output" warnings.
2860 ## In the child process, we intentionally reuse fd 0/1/2 after
2861 ## close_terminal() frees them. This is expected during pty setup
2862 ## and should not warn even when the parent has $^W=1.
2863 184 local $^W = 0;
2864  
2865 184 ▶ if (_debugging) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging()) 0 184 184
2866 _set_child_debug_name(
2867 ref $kid->{VAL} eq "CODE"
2868 ? "CODE"
2869 0 ▶ : basename( $kid->{VAL}->[0] )
Branch: 1 branch
BranchTrueFalseTotal
ref $kid->{'VAL'} eq 'CODE' ? : 0 0 0
2870 );
2871 }
2872  
2873 ## close parent FD's first so they're out of the way.
2874 ## Don't close STDIN, STDOUT, STDERR: they should be inherited or
2875 ## overwritten below.
2876 144 do { $_->{needed} = 1 for @fds{0..2} }
2877 184 ▶ unless $self->{noinherit};
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"noinherit"}) 144 40 184
2878  
2879 184 $fds{$self->{SYNC_WRITER_FD}}{needed} = 1;
2880 184 ▶ $fds{$self->{CODEREF_ERR_FD}}{needed} = 1 if defined $self->{CODEREF_ERR_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"CODEREF_ERR_FD"} 3 181 184
2881 184 ▶ $fds{$self->{DEBUG_FD}}{needed} = 1 if defined $self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"DEBUG_FD"} 0 184 184
2882  
2883 $fds{$_->{TFD}}{needed} = 1
2884 184 foreach grep { defined $_->{TFD} } @{$kid->{OPS} };
2885  
2886  
2887 ## TODO: use the forthcoming IO::Pty to close the terminal and
2888 ## make the first pty for this child the controlling terminal.
2889 ## This will also make it so that pty-laden kids don't cause
2890 ## other kids to lose stdin/stdout/stderr.
2891  
2892 184 ▶ if ( %{ $self->{PTYS} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$self->{"PTYS"};}) 7 177 184
2893 ## Clean up the parent's fds.
2894 7 for ( keys %{ $self->{PTYS} } ) {
2895 7 ▶ _debug "Cleaning up parent's ptty '$_'" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 7 7
2896 7 $self->{PTYS}->{$_}->make_slave_controlling_terminal;
2897 7 my $slave = $self->{PTYS}->{$_}->slave;
2898 7 delete $fds{$self->{PTYS}->{$_}->fileno};
2899 7 close $self->{PTYS}->{$_};
2900 7 $self->{PTYS}->{$_} = $slave;
2901 }
2902  
2903 7 close_terminal;
2904 7 delete @fds{0..2};
2905 }
2906  
2907 184 for my $sibling ( @{ $self->{KIDS} } ) {
2908 206 for ( @{ $sibling->{OPS} } ) {
2909 401 ▶ if ( $_->{TYPE} =~ /^.pty.$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{"TYPE"} =~ /^.pty.$/) 8 393 401
2910 8 $_->{TFD} = $self->{PTYS}->{ $_->{PTY_ID} }->fileno;
2911 8 $fds{$_->{TFD}}{needed} = 1;
2912 }
2913  
2914 }
2915 }
2916  
2917 ## This is crude: we have no way of keeping track of browsing all open
2918 ## fds, so we scan to a fairly high fd.
2919 184 ▶ _debug "open fds: ", join " ", keys %fds if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 184 184
2920  
2921 184 _close( $_ ) foreach grep { ! $fds{$_}{needed} } keys %fds;
2922  
2923 184 ▶ if ( $kid->{ENV} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kid->{"ENV"}) 3 181 184
2924 3 foreach my $k ( keys %{ $kid->{ENV} } ) {
2925 3 $ENV{$k} = $kid->{ENV}{$k};
2926 }
2927 }
2928  
2929 184 for ( @{ $kid->{OPS} } ) {
2930 370 ▶ if ( defined $_->{TFD} ) {
Branch: 4 branches
BranchTrueFalseTotal
if (defined $_->{'TFD'}) { } 349 21 370
elsif ($_->{'TYPE'} eq 'dup') { } 12 9 21
elsif ($_->{'TYPE'} eq 'close') { } 6 3 9
elsif ($_->{'TYPE'} eq 'init') { } 3 0 3
2931  
2932 # we're always creating KFD
2933 349 $fds{$_->{KFD}}{needed} = 1;
2934  
2935 349 ▶ unless ( $_->{TFD} == $_->{KFD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{'TFD'} == $_->{'KFD'}) { } 1 348 349
2936 348 $self->_dup2_gently( $kid->{OPS}, $_->{TFD}, $_->{KFD} );
2937 348 $fds{$_->{TFD}}{lazy_close} = 1;
2938 } else {
2939 1 my $fd = _dup($_->{TFD});
2940 1 $_->{TFD} = $fd;
2941 1 $self->_dup2_gently( $kid->{OPS}, $fd, $_->{KFD} );
2942 1 _close($fd);
2943 }
2944 }
2945 elsif ( $_->{TYPE} eq 'dup' ) {
2946 $self->_dup2_gently( $kid->{OPS}, $_->{KFD1}, $_->{KFD2} )
2947 12 ▶ unless $_->{KFD1} == $_->{KFD2};
Branch: 1 branch
BranchTrueFalseTotal
unless $_->{"KFD1"} == $_->{"KFD2"} 12 0 12
2948 12 $fds{$_->{KFD2}}{needed} = 1;
2949 }
2950 elsif ( $_->{TYPE} eq 'close' ) {
2951 6 for ( $_->{KFD} ) {
2952 6 ▶ if ( $fds{$_} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fds{$_}) 5 1 6
2953 5 _close($_);
2954 5 $_ = undef;
2955 }
2956 }
2957 }
2958 elsif ( $_->{TYPE} eq 'init' ) {
2959 3 $_->{SUB}->();
2960 }
2961 }
2962  
2963 184 _close( $_ ) foreach grep { $fds{$_}{lazy_close} } keys %fds;
2964  
2965 184 ▶ if ( ref $kid->{VAL} ne 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $kid->{"VAL"} ne "CODE") 181 3 184
2966 181 ▶ open $s1, ">&=$self->{SYNC_WRITER_FD}"
Branch: 1 branch
BranchTrueFalseTotal
open $s1, qq[>&=$self->{"SYNC_WRITER_FD"}] or croak("$! setting filehandle to fd SYNC_WRITER_FD") 0 181 181
2967 or croak "$! setting filehandle to fd SYNC_WRITER_FD";
2968 181 fcntl $s1, F_SETFD, 1;
2969  
2970 181 ▶ if ( defined $self->{DEBUG_FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"DEBUG_FD"}) 0 181 181
2971 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
2972 or croak "$! setting filehandle to fd DEBUG_FD";
2973 0 fcntl $s2, F_SETFD, 1;
2974 }
2975  
2976 181 ▶ if (_debugging) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging()) 0 181 181
2977 0 my @cmd = ( $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ] );
2978 0 ▶ _debug 'execing ', join " ", map { /[\s\"]/ ? "'$_'" : $_ } @cmd;
Branch: 1 branch
BranchTrueFalseTotal
/[\s\"]/ ? : 0 0 0
2979 }
2980  
2981 die "exec failed: simulating exec() failure"
2982 181 ▶ if $self->{_simulate_exec_failure};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_simulate_exec_failure"} 0 181 181
2983  
2984 181 _exec $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ];
2985  
2986 0 croak "exec failed: $!";
2987 }
2988 };
2989 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
2990 0 _write $self->{SYNC_WRITER_FD}, $@;
2991 ## Avoid DESTROY.
2992 0 POSIX::_exit(1);
2993 }
2994  
2995 ## We must be executing code in the child, otherwise exec() would have
2996 ## prevented us from being here.
2997 3 _close $self->{SYNC_WRITER_FD};
2998 3 ▶ _debug 'calling fork()ed CODE ref' if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 3 3
2999 3 ▶ POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"DEBUG_FD"} 0 3 3
3000 ## TODO: Overload CORE::GLOBAL::exit...
3001 ## Wrap the coderef in eval so that a die() inside it does not propagate
3002 ## out of _do_kid_and_exit and escape into the parent process's call stack.
3003 ## Without this, the exception would unwind past the fork() point and cause
3004 ## the child to continue executing parent code (GH#97).
3005 3 eval { $kid->{VAL}->() };
3006 0 my $kid_err = $@;
3007  
3008 ## There are bugs in perl closures up to and including 5.6.1
3009 ## that may keep this next line from having any effect, and it
3010 ## won't have any effect if our caller has kept a copy of it, but
3011 ## this may cause the closure to be cleaned up. Maybe.
3012 0 $kid->{VAL} = undef;
3013  
3014 ## GH#122: Propagate the exception back to the parent via a dedicated
3015 ## error pipe. We can't use the sync pipe because it must be closed
3016 ## before running the CODE ref to avoid deadlocks (the parent blocks
3017 ## on the sync pipe, so the child can't do I/O with the parent until
3018 ## the sync pipe is closed).
3019 0 ▶ if ($kid_err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kid_err) 0 0 0
3020 0 ▶ if ( defined $self->{CODEREF_ERR_FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"CODEREF_ERR_FD"}) 0 0 0
3021 0 _write $self->{CODEREF_ERR_FD}, $kid_err;
3022 0 POSIX::close $self->{CODEREF_ERR_FD};
3023 }
3024 0 POSIX::_exit(1);
3025 }
3026  
3027 POSIX::close $self->{CODEREF_ERR_FD}
3028 0 ▶ if defined $self->{CODEREF_ERR_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"CODEREF_ERR_FD"} 0 0 0
3029  
3030 ## Use POSIX::_exit to avoid global destruction, since this might
3031 ## cause DESTROY() to be called on objects created in the parent
3032 ## and thus cause double cleanup. For instance, if DESTROY() unlinks
3033 ## a file in the child, we don't want the parent to suddenly miss
3034 ## it.
3035 0 POSIX::_exit(0);
3036 }
3037  
3038 =pod
3039  
3040 =item start
3041  
3042 $h = start(
3043 \@cmd, \$in, \$out, ...,
3044 timeout( 30, name => "process timeout" ),
3045 $stall_timeout = timeout( 10, name => "stall timeout" ),
3046 );
3047  
3048 $h = start \@cmd, '<', \$in, '|', \@cmd2, ...;
3049  
3050 start() accepts a harness or harness specification and returns a harness
3051 after building all of the pipes and launching (via fork()/exec(), or, maybe
3052 someday, spawn()) all the child processes. It does not send or receive any
3053 data on the pipes, see pump() and finish() for that.
3054  
3055 You may call harness() and then pass its result to start() if you like,
3056 but you only need to if it helps you structure or tune your application.
3057 If you do call harness(), you may skip start() and proceed directly to
3058 pump.
3059  
3060 start() also starts all timers in the harness. See L<IPC::Run::Timer>
3061 for more information.
3062  
3063 start() flushes STDOUT and STDERR to help you avoid duplicate output.
3064 It has no way of asking Perl to flush all your open filehandles, so
3065 you are going to need to flush any others you have open. Sorry.
3066  
3067 Here's how if you don't want to alter the state of $| for your
3068 filehandle:
3069  
3070 $ofh = select HANDLE; $of = $|; $| = 1; $| = $of; select $ofh;
3071  
3072 If you don't mind leaving output unbuffered on HANDLE, you can do
3073 the slightly shorter
3074  
3075 $ofh = select HANDLE; $| = 1; select $ofh;
3076  
3077 Or, you can use IO::Handle's flush() method:
3078  
3079 use IO::Handle;
3080 flush HANDLE;
3081  
3082 Perl needs the equivalent of C's fflush( (FILE *)NULL ).
3083  
3084 =cut
3085  
3086 sub start {
3087  
3088 # $SIG{__DIE__} = sub { my $s = shift; Carp::cluck $s; die $s };
3089 2541 ▶ my $options;
Subroutine start: called CC=52 SCAR=48.7
Pod documented
3090 2541 ▶ if ( @_ && ref $_[-1] eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ref $_[-1] eq "HASH") 0 2541 2541
Condition33%1/3
@_ and ref $_[-1] eq "HASH"
!ll&&!rl&&r
025410
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
3091 0 $options = pop;
3092 0 require Data::Dumper;
3093 0 carp "Passing in options as a hash is deprecated:\n", Data::Dumper::Dumper($options);
3094 }
3095  
3096 2541 my IPC::Run $self;
3097 2541 ▶ if ( @_ == 1 && UNIVERSAL::isa( $_[0], __PACKAGE__ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__)) { } 75 2466 2541
Condition100%3/3
@_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__)
!ll&&!rl&&r
230016675
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
3098 75 $self = shift;
3099 75 $self->{$_} = $options->{$_} for keys %$options;
3100 }
3101 else {
3102 2466 ▶ $self = harness( @_, $options ? $options : () );
Branch: 1 branch
BranchTrueFalseTotal
$options ? : 0 2466 2466
3103 }
3104  
3105 2431 local $cur_self = $self;
3106  
3107 2431 ▶ $self->kill_kill if $self->{STATE} == _started;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"STATE"} == 3 4 2427 2431
3108  
3109 2431 ▶ _debug "** starting" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 2431 2431
3110  
3111 2431 $_->{RESULT} = undef for @{ $self->{KIDS} };
3112  
3113 ## Assume we're not being called from &run. It will correct our
3114 ## assumption if need be. This affects whether &_select_loop clears
3115 ## input queues to '' when they're empty.
3116 2431 $self->{clear_ins} = 1;
3117  
3118 2431 ▶ IPC::Run::Win32Helper::optimize $self
Branch: 1 branch
BranchTrueFalseTotal
if &Win32_MODE() and $IPC::Run::in_run 0 2431 2431
Condition33%1/3
&Win32_MODE() and $IPC::Run::in_run
!ll&&!rl&&r
243100
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
3119 if Win32_MODE && $in_run;
3120  
3121 2431 my @errs;
3122  
3123 2431 for ( @{ $self->{TIMERS} } ) {
3124 404 eval { $_->start };
3125 404 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 404 404
3126 0 push @errs, $@;
3127 0 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3128 }
3129 }
3130  
3131 2431 eval { $self->_open_pipes };
3132 2431 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 67 2364 2431
3133 67 push @errs, $@;
3134 67 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 67 67
3135 }
3136  
3137 2431 ▶ if ( !@errs ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@errs) 2364 67 2431
3138 ## This is a bit of a hack, we should do it for all open filehandles.
3139 ## Since there's no way I know of to enumerate open filehandles, we
3140 ## autoflush STDOUT and STDERR. This is done so that the children don't
3141 ## inherit output buffers chock full o' redundant data. It's really
3142 ## confusing to track that down.
3143 2364 { my $ofh = select STDOUT; my $of = $|; $| = 1; $| = $of; select $ofh; }
3144 2364 { my $ofh = select STDERR; my $of = $|; $| = 1; $| = $of; select $ofh; }
3145 2364 for my $kid ( @{ $self->{KIDS} } ) {
3146 2408 $kid->{RESULT} = undef;
3147 _debug "child: ", _debugstrings( $kid->{VAL} )
3148 2408 ▶ if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2408 2408
3149 2408 eval {
3150 2408 ▶ if ( $self->{_simulate_fork_failure} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_simulate_fork_failure"}) 10 2398 2408
3151 10 $kid->{PID} = undef; # simulate fork() returning undef
3152 10 croak "Cannot allocate memory during fork";
3153 }
3154 2398 ▶ unless (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 2398 2398
3155 2398 $self->_spawn($kid);
3156 }
3157 else {
3158 ## TODO: Test and debug spawning code. Someday.
3159 _debug(
3160 'spawning ',
3161 _debugstrings(
3162 [
3163 $kid->{PATH},
3164 0 @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ]
3165 ]
3166 )
3167 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
3168 ## The external kid wouldn't know what to do with it anyway.
3169 ## This is only used by the "helper" pump processes on Win32.
3170 0 _dont_inherit( $self->{DEBUG_FD} );
3171 ( $kid->{PID}, $kid->{PROCESS} ) = IPC::Run::Win32Helper::win32_spawn(
3172 ref( $kid->{VAL} ) eq "ARRAY"
3173 0 ? [ $kid->{PATH}, @{ $kid->{VAL} }[ 1 .. $#{ $kid->{VAL} } ] ]
3174 : $kid->{VAL},
3175 $kid->{OPS},
3176 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
ref $kid->{'VAL'} eq 'ARRAY' ? : 0 0 0
3177 0 ▶ _debug "spawn() = ", $kid->{PID} if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3178 0 ▶ if ($self->{_sleep_after_win32_spawn}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_sleep_after_win32_spawn"}) 0 0 0
3179 0 sleep $self->{_sleep_after_win32_spawn};
3180 0 ▶ _debug "after sleep $self->{_sleep_after_win32_spawn}"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3181 if _debugging;
3182 }
3183 }
3184 };
3185 2224 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 12 2212 2224
3186 12 push @errs, $@;
3187 12 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 12 12
3188 }
3189 }
3190 }
3191  
3192 ## Close all those temporary filehandles that the kids needed.
3193 2247 for my $pty ( values %{ $self->{PTYS} } ) {
3194 29 ▶ next unless $pty;
Branch: 1 branch
BranchTrueFalseTotal
unless $pty 1 28 29
3195 28 close $pty->slave;
3196 }
3197  
3198 2247 my @closed;
3199 2247 for my $kid ( @{ $self->{KIDS} } ) {
3200 2280 for ( @{ $kid->{OPS} } ) {
3201 4162 my $close_it = eval {
3202 defined $_->{TFD}
3203 && !$_->{DONT_CLOSE}
3204 && !$closed[ $_->{TFD} ]
3205 && ( !Win32_MODE || !$_->{RECV_THROUGH_TEMP_FILE} ) ## Win32 hack
3206 4162 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
defined $_->{"TFD"} and not $_->{"DONT_CLOSE"} and not $closed[$_->{"TFD"}] and not &Win32_MODE() && $_->{"RECV_THROUGH_TEMP_FILE"} 3715 447 4162
Condition66%8/12
defined $_->{'TFD'} && !$_->{'DONT_CLOSE'} && !$closed[$_->{'TFD'}] && !(&Win32_MODE() && $_->{'RECV_THROUGH_TEMP_FILE'})
!ll&&!rl&&r
44703715
defined $_->{"TFD"} and not $_->{"DONT_CLOSE"} and not $closed[$_->{"TFD"}]
!ll&&!rl&&r
44703715
defined $_->{"TFD"} and not $_->{"DONT_CLOSE"}
!ll&&!rl&&r
390573715
&Win32_MODE() && $_->{'RECV_THROUGH_TEMP_FILE'}
!ll&&!rl&&r
371500
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
3207 4162 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 4162 4162
3208 0 push @errs, $@;
3209 0 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3210 }
3211 4162 ▶ if ( $close_it || $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($close_it or $@) 3715 447 4162
Condition66%2/3
$close_it or $@
l!l&&r!l&&!r
37150447
MC/DC50%1/2
$close_it or $@
$close_it $@
Truth table66%2/3
A or B
A= $close_itB= $@
ABresult
1X1
011
000
3212 3715 eval {
3213 ## GH#57: For plain '<' redirects with external Perl
3214 ## handles, use close() on the handle so it is properly
3215 ## invalidated (avoids stale-fd / double-close warnings).
3216 ## Only for TYPE '<' — for '<pipe'/'<blocking_pipe', SOURCE
3217 ## is the *write* end that the caller uses; TFD is the
3218 ## internal read end and must be closed via _close().
3219 3715 ▶ 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 3652 3715
Condition91%11/12
defined $_->{"TYPE"} and $_->{"TYPE"} eq "<" and ref $_->{"SOURCE"} and UNIVERSAL::isa($_->{"SOURCE"}, "GLOB") || UNIVERSAL::isa($_->{"SOURCE"}, "IO::Handle")
!ll&&!rl&&r
266798563
defined $_->{"TYPE"} and $_->{"TYPE"} eq "<" and ref $_->{"SOURCE"}
!ll&&!rl&&r
2618491048
defined $_->{"TYPE"} and $_->{"TYPE"} eq "<"
!ll&&!rl&&r
026181097
UNIVERSAL::isa($_->{"SOURCE"}, "GLOB") or UNIVERSAL::isa($_->{"SOURCE"}, "IO::Handle")
l!l&&r!l&&!r
3429985
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
3220 && $_->{TYPE} eq '<'
3221 && ref $_->{SOURCE}
3222 && ( UNIVERSAL::isa( $_->{SOURCE}, 'GLOB' )
3223 || UNIVERSAL::isa( $_->{SOURCE}, 'IO::Handle' ) ) )
3224 {
3225 63 close $_->{SOURCE};
3226 }
3227 else {
3228 3652 _close( $_->{TFD} );
3229 }
3230 3715 $closed[ $_->{TFD} ] = 1;
3231 3715 $_->{TFD} = undef;
3232 };
3233 3715 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3715 3715
3234 0 push @errs, $@;
3235 0 ▶ _debug 'caught ', $@ if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3236 }
3237 }
3238 }
3239 }
3240 2247 ▶ confess "gak!" unless defined $self->{PIPES};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"PIPES"} 0 2247 2247
3241  
3242 2247 ▶ if (@errs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@errs) 79 2168 2247
3243 79 eval { $self->_cleanup };
3244 79 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 79 79
3245 79 die join( '', @errs );
3246 }
3247  
3248 2168 $self->{STATE} = _started;
3249 2168 return $self;
3250 }
3251  
3252 =item adopt
3253  
3254 Experimental feature. NOT FUNCTIONAL YET, NEED TO CLOSE FDS BETTER IN CHILDREN. SEE t/adopt.t for a test suite.
3255  
3256 =cut
3257  
3258 sub adopt {
3259 1 ▶ my IPC::Run $self = shift;
Subroutine adopt: called CC=3 SCAR=11.0
Pod documented
3260  
3261 1 for my $adoptee (@_) {
3262 1 push @{ $self->{IOS} }, @{ $adoptee->{IOS} };
3263 ## NEED TO RENUMBER THE KIDS!!
3264 1 push @{ $self->{KIDS} }, @{ $adoptee->{KIDS} };
3265 1 push @{ $self->{PIPES} }, @{ $adoptee->{PIPES} };
3266 1 $self->{PTYS}->{$_} = $adoptee->{PTYS}->{$_} for keys %{ $adoptee->{PTYS} };
3267 1 push @{ $self->{TIMERS} }, @{ $adoptee->{TIMERS} };
3268 1 $adoptee->{STATE} = _finished;
3269 }
3270 }
3271  
3272 sub _clobber {
3273 3259 ▶ my IPC::Run $self = shift;
Subroutine _clobber: called CC=11 SCAR=24.3
3274 3259 my ($file) = @_;
3275 3259 ▶ _debug_desc_fd( "closing", $file ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 3259 3259
3276 3259 my $doomed = $file->{FD};
3277 3259 ▶ my $dir = $file->{TYPE} =~ /^</ ? 'WIN' : 'RIN';
Branch: 1 branch
BranchTrueFalseTotal
$file->{'TYPE'} =~ /^</ ? : 991 2268 3259
3278 3259 vec( $self->{$dir}, $doomed, 1 ) = 0;
3279  
3280 # vec( $self->{EIN}, $doomed, 1 ) = 0;
3281 3259 vec( $self->{PIN}, $doomed, 1 ) = 0;
3282 3259 ▶ if ( $file->{TYPE} =~ /^(.)pty.$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($file->{'TYPE'} =~ /^(.)pty.$/) { } 32 3227 3259
elsif (UNIVERSAL::isa($file, 'IPC::Run::IO')) { } 3227 0 3227
3283 32 ▶ if ( $1 eq '>' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($1 eq ">") 21 11 32
3284 ## Only close output ptys. This is so that ptys as inputs are
3285 ## never autoclosed, which would risk losing data that was
3286 ## in the slave->parent queue.
3287 21 ▶ _debug_desc_fd "closing pty", $file if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 21 21
3288 close $self->{PTYS}->{ $file->{PTY_ID} }
3289 21 ▶ if defined $self->{PTYS}->{ $file->{PTY_ID} };
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"PTYS"}{$file->{"PTY_ID"}} 21 0 21
3290 21 $self->{PTYS}->{ $file->{PTY_ID} } = undef;
3291 }
3292 }
3293 elsif ( UNIVERSAL::isa( $file, 'IPC::Run::IO' ) ) {
3294 3227 ▶ $file->close unless $file->{DONT_CLOSE};
Branch: 1 branch
BranchTrueFalseTotal
unless $file->{"DONT_CLOSE"} 3227 0 3227
3295 }
3296 else {
3297 0 _close($doomed);
3298 }
3299  
3300 3259 @{ $self->{PIPES} } = grep
3301 defined $_->{FD} && ( $_->{TYPE} ne $file->{TYPE} || $_->{FD} ne $doomed ),
3302 3259 ▶ @{ $self->{PIPES} };
Condition100%6/6
defined $_->{'FD'} && ($_->{'TYPE'} ne $file->{'TYPE'} || $_->{'FD'} ne $doomed)
!ll&&!rl&&r
3273322510
$_->{"TYPE"} ne $file->{"TYPE"} or $_->{"FD"} ne $doomed
l!l&&r!l&&!r
162988132
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
3303  
3304 3259 $file->{FD} = undef;
3305 }
3306  
3307 sub _select_loop {
3308 3280 ▶ my IPC::Run $self = shift;
Subroutine _select_loop: called CC=74 SCAR=66.5
3309  
3310 # With !defined $SIG{CHLD} (the default), Perl restarts any select() that
3311 # SIGCHLD interrupts. Install a no-op handler, to make select() terminate
3312 # with EINTR, accelerating our reaction. This doesn't help if SIGCHLD
3313 # arrives just before the select() call; https://cr.yp.to/docs/selfpipe.html
3314 # is a way to close that race condition. It doesn't help on Windows, where
3315 # we substitute a low timeout in zero-FD (timeout-only) select(). That
3316 # spends CPU to achieve responsiveness. We could do better there with a
3317 # C-language module that calls OpenProcess(), WSAEventSelect(), and
3318 # WaitForMultipleObjects().
3319 #
3320 # If non-IPC::Run code has installed a handler, via $SIG{CHLD} assignment or
3321 # via POSIX::sigaction(), this statement takes no action, and the existing
3322 # handler helps just like this one would. The cap on $not_forever helps
3323 # when non-IPC::Run code has blocked SIGCHLD, e.g. via POSIX::sigprocmask().
3324 # Override undef, '' and 'DEFAULT' — all of which leave the default
3325 # disposition in effect and would cause Perl to restart select().
3326 ▶ local $SIG{CHLD} = sub { }
Subroutine __ANON__: called CC=1 SCAR=0.0
3327 3280 ▶ unless $SIG{CHLD} && $SIG{CHLD} ne 'DEFAULT';
Branch: 1 branch
BranchTrueFalseTotal
unless $SIG{"CHLD"} and $SIG{"CHLD"} ne "DEFAULT" 3278 2 3280
Condition100%3/3
$SIG{"CHLD"} and $SIG{"CHLD"} ne "DEFAULT"
!ll&&!rl&&r
327712
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
3328  
3329 # When a child exits before consuming all of its stdin, any subsequent
3330 # write to the pipe raises SIGPIPE. With the default disposition that
3331 # kills the parent. Ignore SIGPIPE here so that POSIX::write() instead
3332 # returns -1 with errno EPIPE, which pipe_writer catches and handles by
3333 # closing the pipe gracefully. Honour an existing *custom* handler
3334 # installed by the caller, but override undef, '' and 'DEFAULT' — all
3335 # of which leave the default (fatal) disposition in effect.
3336 local $SIG{PIPE} = 'IGNORE'
3337 3280 ▶ unless $SIG{PIPE} && $SIG{PIPE} ne 'DEFAULT';
Branch: 1 branch
BranchTrueFalseTotal
unless $SIG{"PIPE"} and $SIG{"PIPE"} ne "DEFAULT" 3279 1 3280
Condition100%3/3
$SIG{"PIPE"} and $SIG{"PIPE"} ne "DEFAULT"
!ll&&!rl&&r
3257221
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
3338  
3339 3280 my $io_occurred;
3340  
3341 3280 my $min_select_timeout = 0.01;
3342 3280 my $not_forever = $min_select_timeout;
3343  
3344 SELECT:
3345 3280 ▶ while ( $self->pumpable ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->pumpable) 11675 1530 13205
3346 11675 ▶ if ( $io_occurred && $self->{break_on_io} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($io_occurred and $self->{"break_on_io"}) 401 11274 11675
Condition100%3/3
$io_occurred and $self->{"break_on_io"}
!ll&&!rl&&r
78403434401
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
3347 401 ▶ _debug "exiting _select(): io occurred and break_on_io set"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 401 401
3348 if _debugging_details;
3349 401 last;
3350 }
3351  
3352 11274 ▶ my $timeout = $self->{non_blocking} ? 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'non_blocking'} ? : 1413 9861 11274
3353  
3354 11274 ▶ if ( @{ $self->{TIMERS} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"TIMERS"};}) 1858 9416 11274
3355 1858 my $now = time;
3356 1858 my $time_left;
3357 1858 for ( @{ $self->{TIMERS} } ) {
3358 1858 ▶ next unless $_->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $_->is_running 0 1858 1858
3359 1858 $time_left = $_->check($now);
3360 ## Return when a timer expires
3361 1848 ▶ return if defined $time_left && !$time_left;
Branch: 1 branch
BranchTrueFalseTotal
if defined $time_left and not $time_left 0 1848 1848
Condition33%1/3
defined $time_left and not $time_left
!ll&&!rl&&r
018480
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
3362 1848 ▶ $timeout = $time_left
Branch: 1 branch
BranchTrueFalseTotal
if not defined $timeout or $time_left < $timeout 1344 504 1848
Condition66%2/3
not defined $timeout or $time_left < $timeout
l!l&&r!l&&!r
13440504
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
3363 if !defined $timeout || $time_left < $timeout;
3364 }
3365 }
3366  
3367 ##
3368 ## See if we can unpause any input channels
3369 ##
3370 11264 my $paused = 0;
3371  
3372 11264 for my $file ( @{ $self->{PIPES} } ) {
3373 19782 ▶ next unless $file->{PAUSED} && $file->{TYPE} =~ /^</;
Branch: 1 branch
BranchTrueFalseTotal
unless $file->{"PAUSED"} and $file->{"TYPE"} =~ /^</ 18133 1649 19782
Condition66%2/3
$file->{"PAUSED"} and $file->{"TYPE"} =~ /^</
!ll&&!rl&&r
1813301649
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
3374  
3375 1649 ▶ _debug_desc_fd( "checking for more input", $file ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 1649 1649
3376 1649 my $did;
3377 1649 ▶ 1 while $did = $file->_do_filters($self);
Branch: 1 branch
BranchTrueFalseTotal
$did = $file->_do_filters($self) and do { '???' } 93 1649 1742
3378 1649 ▶ if ( defined $file->{FD} && !defined($did) || $did ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file->{'FD'} and not defined $did or $did) { } 0 1649 1649
Condition50%3/6
defined $file->{"FD"} and not defined $did or $did
l!l&&r!l&&!r
001649
defined $file->{"FD"} and not defined $did
!ll&&!rl&&r
6915800
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
3379 0 ▶ _debug_desc_fd( "unpausing", $file ) if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
3380 0 $file->{PAUSED} = 0;
3381 0 vec( $self->{WIN}, $file->{FD}, 1 ) = 1;
3382  
3383 # vec( $self->{EIN}, $file->{FD}, 1 ) = 1;
3384 0 vec( $self->{PIN}, $file->{FD}, 1 ) = 0;
3385 }
3386 else {
3387 ## This gets incremented occasionally when the IO channel
3388 ## was actually closed. That's a bug, but it seems mostly
3389 ## harmless: it causes us to exit if break_on_io, or to set
3390 ## the timeout to not be forever. I need to fix it, though.
3391 1649 ++$paused;
3392 }
3393 }
3394  
3395 11264 ▶ if (_debugging_details) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging_details()) 0 11264 11264
3396 my $map = join(
3397 '',
3398 map {
3399 0 my $out;
3400 0 ▶ $out = 'r' if vec( $self->{RIN}, $_, 1 );
Branch: 1 branch
BranchTrueFalseTotal
if vec $self->{"RIN"}, $_, 1 0 0 0
3401 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
3402 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
3403 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
3404 0 ▶ $out = '-' unless $out;
Branch: 1 branch
BranchTrueFalseTotal
unless $out 0 0 0
3405 0 $out;
3406 } ( 0 .. 1024 )
3407 );
3408 0 $map =~ s/((?:[a-zA-Z-]|\([^\)]*\)){12,}?)-*$/$1/;
3409 0 ▶ _debug 'fds for select: ', $map if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
3410 }
3411  
3412 ## _do_filters may have closed our last fd, and we need to see if
3413 ## we have I/O, or are just waiting for children to exit.
3414 11264 my $p = $self->pumpable;
3415 11264 ▶ last unless $p;
Branch: 1 branch
BranchTrueFalseTotal
unless $p 0 11264 11264
3416 11264 ▶ if ( $p != 0 && ( !defined $timeout || $timeout > 0.1 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p != 0 and !defined($timeout) || $timeout > "0.1") 9851 1413 11264
Condition83%5/6
$p != 0 and !defined($timeout) || $timeout > "0.1"
!ll&&!rl&&r
086862578
not defined $timeout or $timeout > "0.1"
l!l&&r!l&&!r
850713441413
MC/DC33%1/3
$p != 0 and !defined($timeout) || $timeout > "0.1"
$p != 0 not defined $timeout $timeout > "0.1"
Truth table50%2/4
A and not(B) or C
A= $p != 0B= not defined $timeoutC= $timeout > "0.1"
ABCresult
0XX0
1000
11X1
1011
3417 ## No I/O will wake the select loop up, but we have children
3418 ## lingering, so we need to poll them with a short timeout.
3419 ## Otherwise, assume more input will be coming.
3420  
3421 9851 ▶ 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'}) { } 9851 0 9851
Condition33%3/9
not &Win32_MODE() or $self->{"RIN"} or $self->{"WIN"} or $self->{"EIN"}
l!l&&r!l&&!r
985100
not &Win32_MODE() or $self->{"RIN"} or $self->{"WIN"}
l!l&&r!l&&!r
985100
not &Win32_MODE() or $self->{"RIN"}
l!l&&r!l&&!r
985100
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
3422 9851 $timeout = $not_forever;
3423 9851 $not_forever *= 2;
3424 9851 ▶ $not_forever = 0.5 if $not_forever >= 0.5;
Branch: 1 branch
BranchTrueFalseTotal
if $not_forever >= "0.5" 2860 6991 9851
3425 }
3426 else {
3427 # see above rationale for Windows-specific behavior
3428 0 $timeout = $min_select_timeout;
3429 }
3430 }
3431  
3432 ## Make sure we don't block forever in select() because inputs are
3433 ## paused.
3434 11264 ▶ if ( !defined $timeout && !( @{ $self->{PIPES} } - $paused ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $timeout or @{$self->{"PIPES"};} - $paused) 0 11264 11264
Condition33%1/3
defined $timeout or @{$self->{"PIPES"};} - $paused
l!l&&r!l&&!r
1126400
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
3435 ## Need to return if we're in pump and all input is paused, or
3436 ## we'll loop until all inputs are unpaused, which is darn near
3437 ## forever. And a day.
3438 0 ▶ if ( $self->{break_on_io} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"break_on_io"}) 0 0 0
3439 0 ▶ _debug "exiting _select(): no I/O to do and timeout=forever"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3440 if _debugging;
3441 0 last;
3442 }
3443  
3444 ## Otherwise, assume more input will be coming.
3445 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
3446 0 $timeout = $not_forever;
3447 0 $not_forever *= 2;
3448 0 ▶ $not_forever = 0.5 if $not_forever >= 0.5;
Branch: 1 branch
BranchTrueFalseTotal
if $not_forever >= "0.5" 0 0 0
3449 }
3450 else {
3451 0 $timeout = $min_select_timeout;
3452 }
3453 }
3454  
3455 11264 ▶ _debug 'timeout=', defined $timeout ? $timeout : 'forever'
Branch: 2 branches
BranchTrueFalseTotal
if &_debugging_details() 0 11264 11264
defined $timeout ? : 0 0 0
3456 if _debugging_details;
3457  
3458 11264 my $nfound;
3459 11264 ▶ unless (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 11264 11264
3460 $nfound = select(
3461 $self->{ROUT} = $self->{RIN},
3462 $self->{WOUT} = $self->{WIN},
3463 $self->{EOUT} = $self->{EIN},
3464 11264 $timeout
3465 );
3466 }
3467 else {
3468 0 my @in = map $self->{$_}, qw( RIN WIN EIN );
3469 ## Win32's select() on Win32 seems to die if passed vectors of
3470 ## all 0's. Need to report this when I get back online.
3471 0 for (@in) {
3472 0 ▶ $_ = undef unless index( ( unpack "b*", $_ ), 1 ) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
unless index(unpack("b*", $_), 1) != -1 0 0 0
3473 }
3474  
3475 $nfound = select(
3476 $self->{ROUT} = $in[0],
3477 $self->{WOUT} = $in[1],
3478 0 $self->{EOUT} = $in[2],
3479 $timeout
3480 );
3481  
3482 0 for ( $self->{ROUT}, $self->{WOUT}, $self->{EOUT} ) {
3483 0 ▶ $_ = "" unless defined $_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 0 0 0
3484 }
3485 }
3486 11264 ▶ last if !$nfound && $self->{non_blocking};
Branch: 1 branch
BranchTrueFalseTotal
if not $nfound and $self->{"non_blocking"} 1339 9925 11264
Condition100%3/3
not $nfound and $self->{"non_blocking"}
!ll&&!rl&&r
463652891339
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
3487  
3488 9925 ▶ if ( $nfound < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nfound < 0) 125 9800 9925
3489 125 ▶ if ( $!{EINTR} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($!{'EINTR'}) { } 125 0 125
3490  
3491 # Caught a signal before any FD went ready. Ensure that
3492 # the bit fields reflect "no FDs ready".
3493 125 $self->{ROUT} = $self->{WOUT} = $self->{EOUT} = '';
3494 125 $nfound = 0;
3495 }
3496 else {
3497 0 croak "$! in select";
3498 }
3499 }
3500 ## TODO: Analyze the EINTR failure mode and see if this patch
3501 ## is adequate and optimal.
3502 ## TODO: Add an EINTR test to the test suite.
3503  
3504 9925 ▶ if (_debugging_details) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_debugging_details()) 0 9925 9925
3505 my $map = join(
3506 '',
3507 map {
3508 0 my $out;
3509 0 ▶ $out = 'r' if vec( $self->{ROUT}, $_, 1 );
Branch: 1 branch
BranchTrueFalseTotal
if vec $self->{"ROUT"}, $_, 1 0 0 0
3510 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
3511 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
3512 0 ▶ $out = '-' unless $out;
Branch: 1 branch
BranchTrueFalseTotal
unless $out 0 0 0
3513 0 $out;
3514 } ( 0 .. 128 )
3515 );
3516 0 $map =~ s/((?:[a-zA-Z-]|\([^\)]*\)){12,}?)-*$/$1/;
3517 0 _debug "selected ", $map;
3518 }
3519  
3520 ## Need to copy since _clobber alters @{$self->{PIPES}}.
3521 ## TODO: Rethink _clobber(). Rethink $file->{PAUSED}, too.
3522 9925 my @pipes = @{ $self->{PIPES} };
3523 9925 ▶ $io_occurred = $_->poll($self) ? 1 : $io_occurred for @pipes;
Branch: 1 branch
BranchTrueFalseTotal
$_->poll($self) ? : 2542 13662 16204
3524  
3525 }
3526  
3527 3270 return;
3528 }
3529  
3530 sub _cleanup {
3531 2297 ▶ my IPC::Run $self = shift;
Subroutine _cleanup: called CC=28 SCAR=34.2
3532 2297 ▶ _debug "cleaning up" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2297 2297
3533  
3534 2297 for ( values %{ $self->{PTYS} } ) {
3535 29 ▶ next unless ref $_;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $_ 22 7 29
3536 7 eval {
3537 7 ▶ _debug "closing slave fd ", fileno $_->slave if _debugging_data;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 7 7
3538 7 close $_->slave;
3539 };
3540 7 ▶ carp $@ . " while closing ptys" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
3541 7 eval {
3542 7 ▶ _debug "closing master fd ", fileno $_ if _debugging_data;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_data() 0 7 7
3543 7 close $_;
3544 };
3545 7 ▶ carp $@ . " closing ptys" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
3546 }
3547  
3548 2297 ▶ _debug "cleaning up pipes" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2297 2297
3549 ## _clobber modifies PIPES
3550 2297 ▶ $self->_clobber( $self->{PIPES}->[0] ) while @{ $self->{PIPES} };
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{"PIPES"};} and do { $self->_clobber($self->{"PIPES"}[0]) } 44 2297 2341
3551  
3552 # reap kids
3553 2297 my @coderef_exceptions;
3554 2297 for my $kid ( @{ $self->{KIDS} } ) {
3555 2333 ▶ if ( !defined $kid->{PID} || !length $kid->{PID} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $kid->{'PID'} && length $kid->{'PID'}) { } 77 2256 2333
Condition100%3/3
defined $kid->{'PID'} && length $kid->{'PID'}
!ll&&!rl&&r
10672256
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
3556 77 ▶ _debug 'never ran child ', $kid->{NUM}, ", can't reap"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 77 77
3557 if _debugging;
3558 77 for my $op ( @{ $kid->{OPS} } ) {
3559 _close( $op->{TFD} )
3560 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
3561 }
3562 }
3563 else {
3564 2256 _waitpid( $kid, 0 );
3565 }
3566  
3567 ## GH#122: Read exception from CODE ref error pipe after the child
3568 ## has exited. The pipe is guaranteed to have been closed by the
3569 ## child's POSIX::_exit(), so _read() will not block.
3570 2333 ▶ if ( defined $kid->{CODEREF_ERR_FD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $kid->{"CODEREF_ERR_FD"}) 343 1990 2333
3571 343 my $err = _read $kid->{CODEREF_ERR_FD};
3572 343 POSIX::close $kid->{CODEREF_ERR_FD};
3573 343 delete $kid->{CODEREF_ERR_FD};
3574 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
3575 }
3576 }
3577 2297 ▶ $self->{CODEREF_EXCEPTIONS} = \@coderef_exceptions if @coderef_exceptions;
Branch: 1 branch
BranchTrueFalseTotal
if @coderef_exceptions 88 2209 2297
3578  
3579 # OPS cleanup. Kids may share an OPS object; search for "also to write".
3580 # Example harness: run(['echo',1], '&', ['echo',2], '>', \$out). Hence,
3581 # this starts after the last reap.
3582 2297 for my $kid ( @{ $self->{KIDS} } ) {
3583  
3584 2333 ▶ _debug "cleaning up filters at kid ", $kid->{NUM} if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2333 2333
3585 2333 for my $op ( @{ $kid->{OPS} } ) {
3586 4162 @{ $op->{FILTERS} } = grep {
3587 4444 my $filter = $_;
3588 4444 !grep $filter == $_, @{ $self->{TEMP_FILTERS} };
3589 4162 } @{ $op->{FILTERS} };
3590 }
3591  
3592 2333 for my $op ( @{ $kid->{OPS} } ) {
3593 4162 ▶ $op->_cleanup($self) if UNIVERSAL::isa( $op, "IPC::Run::IO" );
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($op, "IPC::Run::IO") 3875 287 4162
3594 }
3595 }
3596 2297 $self->{STATE} = _finished;
3597 2297 @{ $self->{TEMP_FILTERS} } = ();
3598 2297 ▶ _debug "done cleaning up" if _debugging_details;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2297 2297
3599  
3600 2297 ▶ POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"DEBUG_FD"} 0 2297 2297
3601 2297 $self->{DEBUG_FD} = undef;
3602 }
3603  
3604 =pod
3605  
3606 =item pump
3607  
3608 pump $h;
3609 $h->pump;
3610  
3611 Pump accepts a single parameter harness. It blocks until it delivers some
3612 input or receives some output. It returns TRUE if there is still input or
3613 output to be done, FALSE otherwise.
3614  
3615 pump() will automatically call start() if need be, so you may call harness()
3616 then proceed to pump() if that helps you structure your application.
3617  
3618 If pump() is called after all harnessed activities have completed, a "process
3619 ended prematurely" exception to be thrown. This allows for simple scripting
3620 of external applications without having to add lots of error handling code at
3621 each step of the script:
3622  
3623 $h = harness \@smbclient, \$in, \$out, $err;
3624  
3625 $in = "cd /foo\n";
3626 $h->pump until $out =~ /^smb.*> \Z/m;
3627 die "error cding to /foo:\n$out" if $out =~ "ERR";
3628 $out = '';
3629  
3630 $in = "mget *\n";
3631 $h->pump until $out =~ /^smb.*> \Z/m;
3632 die "error retrieving files:\n$out" if $out =~ "ERR";
3633  
3634 $h->finish;
3635  
3636 warn $err if $err;
3637  
3638 =cut
3639  
3640 sub pump {
3641 1771 ▶ die "pump() takes only a single harness as a parameter"
Subroutine pump: called CC=6 SCAR=19.2
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 and UNIVERSAL::isa($_[0], __PACKAGE__) 0 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
3642 unless @_ == 1 && UNIVERSAL::isa( $_[0], __PACKAGE__ );
3643  
3644 1771 my IPC::Run $self = shift;
3645  
3646 1771 local $cur_self = $self;
3647  
3648 1771 ▶ _debug "** pumping"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 1771 1771
3649 if _debugging;
3650  
3651 1771 ▶ $self->start if $self->{STATE} < _started;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"STATE"} < 3 0 1771 1771
3652 1771 ▶ croak "process ended prematurely" unless $self->pumpable;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->pumpable 0 1771 1771
3653  
3654 1771 $self->{auto_close_ins} = 0;
3655 1771 $self->{break_on_io} = 1;
3656 1771 $self->_select_loop;
3657 1762 return $self->pumpable;
3658 }
3659  
3660 =pod
3661  
3662 =item pump_nb
3663  
3664 pump_nb $h;
3665 $h->pump_nb;
3666  
3667 "pump() non-blocking", pumps if anything's ready to be pumped, returns
3668 immediately otherwise. This is useful if you're doing some long-running
3669 task in the foreground, but don't want to starve any child processes.
3670  
3671 =cut
3672  
3673 sub pump_nb {
3674 1403 ▶ my IPC::Run $self = shift;
Subroutine pump_nb: called CC=2 SCAR=7.0
Pod documented
3675  
3676 1403 $self->{non_blocking} = 1;
3677 1403 my $r = eval { $self->pump };
3678 1403 $self->{non_blocking} = 0;
3679 1403 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1403 1403
3680 1403 return $r;
3681 }
3682  
3683 =pod
3684  
3685 =item close_stdin
3686  
3687 $h->close_stdin;
3688  
3689 Closes the input pipe(s) to the child process(es), signaling EOF on
3690 the child's STDIN. Does B<not> wait for the child to finish or drain
3691 remaining output. After calling this, the caller can continue to
3692 C<pump()> to retrieve output incrementally.
3693  
3694 This is useful when streaming large amounts of data through a child
3695 process (e.g., decompression) where you want to signal end-of-input
3696 but continue draining output without buffering it all in memory:
3697  
3698 my ( $in, $out ) = ( '', '' );
3699 my $h = start \@cmd, \$in, \$out, timeout( 30 );
3700  
3701 while ( read_more_input_into( $in ) ) {
3702 $h->pump;
3703 process_output( $out ) if length $out;
3704 $out = '';
3705 }
3706  
3707 $h->close_stdin;
3708  
3709 while ( $h->pumpable ) {
3710 $h->pump;
3711 process_output( $out ) if length $out;
3712 $out = '';
3713 }
3714  
3715 $h->finish;
3716  
3717 B<Note:> Always use a C<timeout()> with this pattern. Without one, the
3718 C<pump()> calls can deadlock if the child blocks on writing output while
3719 you are blocked trying to write input (or vice versa).
3720  
3721 Without C<close_stdin()>, calling C<finish()> would accumulate all
3722 remaining output in C<$out> before returning, potentially exhausting
3723 memory for children that produce large output (like decompressors).
3724  
3725 Returns the harness object for chaining.
3726  
3727 =cut
3728  
3729 sub close_stdin {
3730 48 ▶ my IPC::Run $self = shift;
Subroutine close_stdin: called CC=5 SCAR=16.2
Pod documented
3731  
3732 48 local $cur_self = $self;
3733  
3734 48 ▶ croak "harness has not been started" unless $self->{STATE} >= _started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} >= 3 0 48 48
3735  
3736 48 ▶ _debug "** closing stdin" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 48 48
3737  
3738 # Match all input pipe types: '<' (plain), '<pipe', '<pty<', etc.
3739 # _clobber() handles each type appropriately: for regular pipes it
3740 # closes the fd (signaling EOF to the child); for input ptys it
3741 # removes them from the select vectors without closing the pty
3742 # master (consistent with _clobber's existing pty safety logic).
3743 48 for my $pipe ( @{ $self->{PIPES} } ) {
3744 50 ▶ next unless $pipe->{TYPE} =~ /^</;
Branch: 1 branch
BranchTrueFalseTotal
unless $pipe->{"TYPE"} =~ /^</ 8 42 50
3745 42 $self->_clobber($pipe);
3746 }
3747  
3748 48 return $self;
3749 }
3750  
3751 =pod
3752  
3753 =item started
3754  
3755 Returns TRUE if the harness has been started and has not yet finished.
3756 This is useful when a harness may or may not have been started by the
3757 caller, and you want to conditionally start it:
3758  
3759 $h->start unless $h->started;
3760  
3761 =cut
3762  
3763 sub started {
3764 13 ▶ my IPC::Run $self = shift;
Subroutine started: called CC=1 SCAR=0.0
Pod documented
3765 13 return $self->{STATE} >= _started;
3766 }
3767  
3768 =item pumpable
3769  
3770 Returns TRUE if calling pump() won't throw an immediate "process ended
3771 prematurely" exception. This means that there are open I/O channels or
3772 active processes. May yield the parent processes' time slice for 0.01
3773 second if all pipes are to the child and all are paused. In this case
3774 we can't tell if the child is dead, so we yield the processor and
3775 then attempt to reap the child in a nonblocking way.
3776  
3777 To wait for child processes to exit during an event loop, poll
3778 C<$h->pumpable> until it returns false, then call C<finish>.
3779 See also L</finished> to test whether the harness has already been
3780 finished.
3781  
3782 =cut
3783  
3784 ## Undocumented feature (don't depend on it outside this module):
3785 ## returns -1 if we have I/O channels open, or >0 if no I/O channels
3786 ## open, but we have kids running. This allows the select loop
3787 ## to poll for child exit.
3788 sub pumpable {
3789 31186 ▶ my IPC::Run $self = shift;
Subroutine pumpable: called CC=4 SCAR=13.9
Pod documented
3790  
3791 ## There's a catch-22 we can get in to if there is only one pipe left
3792 ## open to the child and it's paused (ie the SCALAR it's tied to
3793 ## is ''). It's paused, so we're not select()ing on it, so we don't
3794 ## check it to see if the child attached to it is alive and it stays
3795 ## in @{$self->{PIPES}} forever. So, if all pipes are paused, see if
3796 ## we can reap the child.
3797 31186 ▶ return -1 if grep !$_->{PAUSED}, @{ $self->{PIPES} };
Branch: 1 branch
BranchTrueFalseTotal
if grep((!$_->{"PAUSED"}), @{$$self{"PIPES"};}) 26827 4359 31186
3798  
3799 ## See if the child is dead.
3800 4359 $self->reap_nb;
3801 4359 ▶ return 0 unless $self->_running_kids;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_running_kids 3051 1308 4359
3802  
3803 ## If we reap_nb and it's not dead yet, yield to it to see if it
3804 ## exits.
3805 ##
3806 ## A better solution would be to unpause all the pipes, but I tried that
3807 ## and it never errored on linux. Sigh.
3808 1308 select undef, undef, undef, 0.0001;
3809  
3810 ## try again
3811 1308 $self->reap_nb;
3812 1308 ▶ return 0 unless $self->_running_kids;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_running_kids 93 1215 1308
3813  
3814 1215 return -1; ## There are pipes waiting
3815 }
3816  
3817 sub _running_kids {
3818 5738 ▶ my IPC::Run $self = shift;
Subroutine _running_kids: called CC=2 SCAR=7.0
3819 return grep
3820 defined $_->{PID} && !defined $_->{RESULT},
3821 5738 ▶ @{ $self->{KIDS} };
Condition66%2/3
defined $_->{'PID'} && !defined($_->{'RESULT'})
!ll&&!rl&&r
032582531
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
3822 }
3823  
3824 =pod
3825  
3826 =item reap_nb
3827  
3828 Attempts to reap child processes, but does not block.
3829  
3830 Does not currently take any parameters, one day it will allow specific
3831 children to be reaped.
3832  
3833 Only call this from a signal handler if your C<perl> is recent enough
3834 to have safe signal handling (5.6.1 did not, IIRC, but it was being discussed
3835 on perl5-porters). Calling this (or doing any significant work) in a signal
3836 handler on older C<perl>s is asking for seg faults.
3837  
3838 =cut
3839  
3840 228 my $still_runnings;
3841  
3842 sub reap_nb {
3843 5738 ▶ my IPC::Run $self = shift;
Subroutine reap_nb: called CC=2 SCAR=6.9
Pod documented
3844  
3845 5738 local $cur_self = $self;
3846  
3847 ## No more pipes, look to see if all the kids yet live, reaping those
3848 ## that haven't. I'd use $SIG{CHLD}/$SIG{CLD}, but that's broken
3849 ## on older (SYSV) platforms and perhaps less portable than waitpid().
3850 ## This could be slow with a lot of kids, but that's rare and, well,
3851 ## a lot of kids is slow in the first place.
3852 ## Oh, and this keeps us from reaping other children the process
3853 ## may have spawned.
3854 5738 for my $kid ( @{ $self->{KIDS} } ) {
3855 5789 _waitpid( $kid, 1 );
3856 }
3857 }
3858  
3859 # Support routine (non-method) for waitpid() or platform's equivalent. Sets $?
3860 # and $_[0]->{RESULT} iff the kid exited.
3861 sub _waitpid {
3862 8045 ▶ my ( $kid, $nohang ) = @_;
Subroutine _waitpid: called CC=23 SCAR=49.2
3863  
3864 8045 ▶ if (Win32_MODE) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Win32_MODE()) { } 0 8045 8045
3865 0 require Win32::Process;
3866  
3867 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
3868 0 ▶ my $wait_timeout = $nohang ? 0 : Win32::Process::INFINITE();
Branch: 1 branch
BranchTrueFalseTotal
$nohang ? : 0 0 0
3869 0 ▶ unless ( $kid->{PROCESS}->Wait($wait_timeout) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($kid->{"PROCESS"}->Wait($wait_timeout)) 0 0 0
3870 0 ▶ confess "kid $kid->{PID} still running after indefinite wait"
Branch: 1 branch
BranchTrueFalseTotal
unless $nohang 0 0 0
3871 unless $nohang;
3872 0 ▶ _debug "kid $kid->{NUM} ($kid->{PID}) still running"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 0 0
3873 if _debugging_details;
3874 0 return;
3875 }
3876  
3877 0 ▶ _debug "kid $kid->{NUM} ($kid->{PID}) exited"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 0 0
3878 if _debugging;
3879  
3880 0 my $native_result;
3881 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
3882 or croak "$! while GetExitCode()ing for Win32 process";
3883  
3884 0 ▶ unless ( defined $native_result ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $native_result) { } 0 0 0
3885 0 $kid->{RESULT} = "0 but true";
3886 0 $? = $kid->{RESULT} = 0x0F;
3887 }
3888 else {
3889 0 my $win32_full_result = $native_result << 8;
3890 0 ▶ if ( $win32_full_result >> 8 != $native_result ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($win32_full_result >> 8 != $native_result) 0 0 0
3891  
3892 # !USE_64_BIT_INT build and exit code > 0xFFFFFF
3893 0 require Math::BigInt;
3894 0 $win32_full_result = Math::BigInt->new($native_result);
3895 0 $win32_full_result->blsft(8);
3896 }
3897 0 $? = $kid->{RESULT} = $win32_full_result;
3898 }
3899 }
3900 else {
3901 8045 ▶ return if !defined $kid->{PID} || defined $kid->{RESULT};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $kid->{"PID"} or defined $kid->{"RESULT"} 3319 4726 8045
Condition66%2/3
not defined $kid->{"PID"} or defined $kid->{"RESULT"}
l!l&&r!l&&!r
033194726
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
3902 4726 ▶ my $pid = waitpid $kid->{PID}, $nohang ? POSIX::WNOHANG() : 0;
Branch: 1 branch
BranchTrueFalseTotal
$nohang ? : 4105 621 4726
3903 4726 ▶ unless ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 2531 2195 4726
3904 2531 ▶ confess "kid $kid->{PID} still running after indefinite wait"
Branch: 1 branch
BranchTrueFalseTotal
unless $nohang 0 2531 2531
3905 unless $nohang;
3906 2531 ▶ _debug "$kid->{NUM} ($kid->{PID}) still running"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging_details() 0 2531 2531
3907 if _debugging_details;
3908 2531 return;
3909 }
3910  
3911 2195 ▶ if ( $pid < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid < 0) { } 2 2193 2195
3912 2 ▶ _debug "No such process: $kid->{PID}\n" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 2 2
3913 2 $kid->{RESULT} = "unknown result, unknown PID";
3914 }
3915 else {
3916 2193 ▶ _debug "kid $kid->{NUM} ($kid->{PID}) exited"
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 2193 2193
3917 if _debugging;
3918  
3919 confess "waitpid returned the wrong PID: $pid instead of $kid->{PID}"
3920 2193 ▶ unless $pid == $kid->{PID};
Branch: 1 branch
BranchTrueFalseTotal
unless $pid == $kid->{"PID"} 0 2193 2193
3921 2193 ▶ _debug "$kid->{PID} returned $?\n" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 2193 2193
3922 2193 $kid->{RESULT} = $?;
3923 }
3924 }
3925 }
3926  
3927 =pod
3928  
3929 =item finish
3930  
3931 This must be called after the last start() or pump() call for a harness,
3932 or your system will accumulate defunct processes and you may "leak"
3933 file descriptors.
3934  
3935 finish() returns TRUE if all children returned 0 (and were not signaled and did
3936 not coredump, ie ! $?), and FALSE otherwise (this is like run(), and the
3937 opposite of system()).
3938  
3939 Once a harness has been finished, it may be run() or start()ed again,
3940 including by pump()s auto-start.
3941  
3942 If this throws an exception rather than a normal exit, the harness may
3943 be left in an unstable state, it's best to kill the harness to get rid
3944 of all the child processes, etc.
3945  
3946 Specifically, if a timeout expires in finish(), finish() will not
3947 kill all the children. Call C<< $h->kill_kill >> in this case if you care.
3948 This differs from the behavior of L</run>.
3949  
3950 =cut
3951  
3952 sub finish {
3953 2156 ▶ my IPC::Run $self = shift;
Subroutine finish: called CC=10 SCAR=23.2
Pod documented
3954 2156 ▶ my $options = @_ && ref $_[-1] eq 'HASH' ? pop : {};
Branch: 1 branch
BranchTrueFalseTotal
@_ && ref $_[-1] eq 'HASH' ? : 0 2156 2156
Condition33%1/3
@_ and ref $_[-1] eq "HASH"
!ll&&!rl&&r
215600
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
3955  
3956 2156 local $cur_self = $self;
3957  
3958 2156 ▶ _debug "** finishing" if _debugging;
Branch: 1 branch
BranchTrueFalseTotal
if &_debugging() 0 2156 2156
3959  
3960 2156 $self->{non_blocking} = 0;
3961 2156 $self->{auto_close_ins} = 1;
3962 2156 $self->{break_on_io} = 0;
3963  
3964 # We don't alter $self->{clear_ins}, start() and run() control it.
3965  
3966 2156 ▶ if ( %{ $self->{PTYS} } || @{ $self->{PIPES} } || @{ $self->{TIMERS} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$self->{"PTYS"};} or @{$self->{"PIPES"};} or @{$self->{"TIMERS"};}) 1503 625 2128
Condition100%6/6
%{$self->{"PTYS"};} or @{$self->{"PIPES"};} or @{$self->{"TIMERS"};}
l!l&&r!l&&!r
146566625
%{$self->{"PTYS"};} or @{$self->{"PIPES"};}
l!l&&r!l&&!r
281437691
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
3967 1531 ▶ while ( $self->pumpable ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->pumpable) 1509 1530 3039
3968 1509 $self->_select_loop($options);
3969 }
3970 }
3971 2155 $self->_cleanup;
3972  
3973 ## GH#122: Propagate CODE ref exceptions to the caller.
3974 2155 ▶ if ( $self->{CODEREF_EXCEPTIONS} && @{ $self->{CODEREF_EXCEPTIONS} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"CODEREF_EXCEPTIONS"} and @{$self->{"CODEREF_EXCEPTIONS"};}) 88 2067 2155
Condition66%2/3
$self->{"CODEREF_EXCEPTIONS"} and @{$self->{"CODEREF_EXCEPTIONS"};}
!ll&&!rl&&r
2067088
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
3975 88 croak $self->{CODEREF_EXCEPTIONS}->[0];
3976 }
3977  
3978 2067 return !$self->full_result;
3979 }
3980  
3981 =pod
3982  
3983 =item result
3984  
3985 $h->result;
3986  
3987 Returns the first non-zero result code (ie $? >> 8). See L</full_result> to
3988 get the $? value for a child process.
3989  
3990 To get the result of a particular child, do:
3991  
3992 $h->result( 0 ); # first child's $? >> 8
3993 $h->result( 1 ); # second child
3994  
3995 or
3996  
3997 ($h->results)[0]
3998 ($h->results)[1]
3999  
4000 Returns undef if no child processes were spawned and no child number was
4001 specified. Throws an exception if an out-of-range child number is passed.
4002  
4003 Note that C<result> returns C<undef> both when no children have exited and
4004 when all children exited with a zero exit code. Use L</finished> to
4005 determine whether the harness has actually completed, or use L</results> to
4006 get the exit codes of all children (including zeros).
4007  
4008 =cut
4009  
4010 sub _assert_finished {
4011 2101 ▶ my IPC::Run $self = $_[0];
Subroutine _assert_finished: called CC=3 SCAR=11.7
4012  
4013 2101 ▶ croak "Harness not run" unless $self->{STATE} >= _finished;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} >= 2 0 2101 2101
4014 2101 ▶ croak "Harness not finished running" unless $self->{STATE} == _finished;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} == 2 0 2101 2101
4015 }
4016  
4017 sub _child_result {
4018 19 ▶ my IPC::Run $self = shift;
Subroutine _child_result: called CC=3 SCAR=12.3
4019  
4020 19 my ($which) = @_;
4021 croak(
4022 "Only ",
4023 0 scalar( @{ $self->{KIDS} } ),
4024 " child processes, no process $which"
4025 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
4026 19 return $self->{KIDS}->[$which]->{RESULT};
4027 }
4028  
4029 # When $SIG{CHLD} is 'IGNORE', waitpid returns -1 and RESULT is set to
4030 # the string "unknown result, unknown PID". Using that string in numeric
4031 # context (>> 8, 0+, boolean) triggers a warning. This helper silences it.
4032 sub _numeric_result {
4033 228 ▶ no warnings 'numeric';
Subroutine BEGIN: called CC=1 SCAR=0.0
4034 2135 ▶ return 0 + $_[0];
Subroutine _numeric_result: called CC=1 SCAR=0.0
4035 }
4036  
4037 sub result {
4038 15 ▶ &_assert_finished;
Subroutine result: called CC=5 SCAR=16.1
Pod documented
4039 15 my IPC::Run $self = shift;
4040  
4041 15 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 10 5 15
4042 10 my ($which) = @_;
4043 10 return _numeric_result( $self->_child_result($which) ) >> 8;
4044 }
4045 else {
4046 5 ▶ return undef unless @{ $self->{KIDS} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"KIDS"};} 0 5 5
4047 5 for ( @{ $self->{KIDS} } ) {
4048 13 my $candidate = _numeric_result( $_->{RESULT} ) >> 8;
4049 13 ▶ return $candidate if $candidate;
Branch: 1 branch
BranchTrueFalseTotal
if $candidate 2 11 13
4050 }
4051 }
4052 }
4053  
4054 =pod
4055  
4056 =item results
4057  
4058 Returns a list of child exit values. See L</full_results> if you want to
4059 know if a signal killed the child.
4060  
4061 Throws an exception if the harness is not in a finished state.
4062
4063 =cut
4064  
4065 sub results {
4066 4 ▶ &_assert_finished;
Subroutine results: called CC=1 SCAR=0.0
Pod documented
4067 4 my IPC::Run $self = shift;
4068  
4069 4 return map { _numeric_result( $_->{RESULT} ) >> 8 } @{ $self->{KIDS} };
4070 }
4071  
4072 =pod
4073  
4074 =item full_result
4075  
4076 $h->full_result;
4077  
4078 Returns the first non-zero $?. See L</result> to get the first $? >> 8
4079 value for a child process.
4080  
4081 To get the result of a particular child, do:
4082  
4083 $h->full_result( 0 ); # first child's $?
4084 $h->full_result( 1 ); # second child
4085  
4086 or
4087  
4088 ($h->full_results)[0]
4089 ($h->full_results)[1]
4090  
4091 Returns undef if no child processes were spawned and no child number was
4092 specified. Throws an exception if an out-of-range child number is passed.
4093  
4094 =cut
4095  
4096 sub full_result {
4097 2079 ▶ &_assert_finished;
Subroutine full_result: called CC=5 SCAR=16.1
Pod documented
4098  
4099 2079 my IPC::Run $self = shift;
4100  
4101 2079 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 9 2070 2079
4102 9 my ($which) = @_;
4103 9 return $self->_child_result($which);
4104 }
4105 else {
4106 2070 ▶ return undef unless @{ $self->{KIDS} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"KIDS"};} 2 2068 2070
4107 2068 for ( @{ $self->{KIDS} } ) {
4108 2102 ▶ return $_->{RESULT} if _numeric_result( $_->{RESULT} );
Branch: 1 branch
BranchTrueFalseTotal
if _numeric_result($_->{"RESULT"}) 537 1565 2102
4109 }
4110 }
4111 }
4112  
4113 =pod
4114  
4115 =item full_results
4116  
4117 Returns a list of child exit values as returned by C<wait>. See L</results>
4118 if you don't care about coredumps or signals.
4119  
4120 Throws an exception if the harness is not in a finished state.
4121
4122 =cut
4123  
4124 sub full_results {
4125 3 ▶ &_assert_finished;
Subroutine full_results: called CC=3 SCAR=11.2
Pod documented
4126 3 my IPC::Run $self = shift;
4127  
4128 3 ▶ croak "Harness not run" unless $self->{STATE} >= _finished;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} >= 2 0 3 3
4129 3 ▶ croak "Harness not finished running" unless $self->{STATE} == _finished;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"STATE"} == 2 0 3 3
4130  
4131 3 return map $_->{RESULT}, @{ $self->{KIDS} };
4132 }
4133  
4134 =pod
4135  
4136 =item pid
4137  
4138 $h->pid;
4139  
4140 Returns the process ID of the first child process, or undef if no child
4141 processes have been spawned yet.
4142  
4143 To get the PID of a particular child, do:
4144  
4145 $h->pid( 0 ); # first child's PID
4146 $h->pid( 1 ); # second child's PID
4147  
4148 or
4149  
4150 ($h->pids)[0]
4151 ($h->pids)[1]
4152  
4153 PIDs are available as soon as the harness has been started with L</start>.
4154  
4155 =cut
4156  
4157 sub pid {
4158 28 ▶ my IPC::Run $self = shift;
Subroutine pid: called CC=7 SCAR=21.3
Pod documented
4159  
4160 28 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 8 20 28
4161 8 my ($which) = @_;
4162 croak(
4163 "Only ",
4164 0 scalar( @{ $self->{KIDS} } ),
4165 " child processes, no process $which"
4166 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
4167 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
4168 }
4169 else {
4170 20 ▶ return undef unless @{ $self->{KIDS} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"KIDS"};} 0 20 20
4171 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
4172 }
4173 }
4174  
4175 =pod
4176  
4177 =item pids
4178  
4179 Returns a list of child process IDs. See L</pid> to get the PID of a
4180 specific child process.
4181  
4182 PIDs are available as soon as the harness has been started with L</start>.
4183  
4184 =cut
4185  
4186 sub pids {
4187 8 ▶ my IPC::Run $self = shift;
Subroutine pids: called CC=2 SCAR=7.0
Pod documented
4188  
4189 8 ▶ return map { $_->{PID} || undef } @{ $self->{KIDS} };
Branch: 1 branch
BranchTrueFalseTotal
$_->{"PID"} or undef 0 11 11
4190 }
4191  
4192 =pod
4193  
4194 =item is_running
4195  
4196 $h->is_running;
4197  
4198 Returns true if the harness is currently running (i.e. after L</start> and
4199 before L</finish>), false otherwise.
4200  
4201 =cut
4202  
4203 sub is_running {
4204 7 ▶ my IPC::Run $self = shift;
Subroutine is_running: called CC=1 SCAR=0.0
Pod documented
4205  
4206 7 return $self->{STATE} == _started;
4207 }
4208  
4209 =pod
4210  
4211 =item full_path
4212  
4213 $h->full_path;
4214  
4215 Returns the full path to the executable of the first child process, as
4216 resolved by searching C<PATH> when the harness is started with L</start>.
4217 Returns undef if the first child is a code reference (not an external
4218 command), or if the harness has not been started yet.
4219  
4220 To get the full path of a particular child, do:
4221  
4222 $h->full_path( 0 ); # first child's executable path
4223 $h->full_path( 1 ); # second child's executable path
4224  
4225 or
4226  
4227 ($h->full_paths)[0]
4228 ($h->full_paths)[1]
4229  
4230 =cut
4231  
4232 sub full_path {
4233 2 ▶ my IPC::Run $self = shift;
Subroutine full_path: called CC=5 SCAR=17.0
Pod documented
4234  
4235 2 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 1 1 2
4236 1 my ($which) = @_;
4237 croak(
4238 "Only ",
4239 0 scalar( @{ $self->{KIDS} } ),
4240 " child processes, no process $which"
4241 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
4242 1 return $self->{KIDS}->[$which]->{PATH};
4243 }
4244 else {
4245 1 ▶ return undef unless @{ $self->{KIDS} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"KIDS"};} 0 1 1
4246 1 return $self->{KIDS}->[0]->{PATH};
4247 }
4248 }
4249  
4250 =pod
4251  
4252 =item full_paths
4253  
4254 Returns a list of full paths to the executables of all child processes.
4255 Children that are code references (not external commands) will have C<undef>
4256 in the corresponding position.
4257  
4258 =cut
4259  
4260 sub full_paths {
4261 1 ▶ my IPC::Run $self = shift;
Subroutine full_paths: called CC=1 SCAR=0.0
Pod documented
4262  
4263 1 return map { $_->{PATH} } @{ $self->{KIDS} };
4264 }
4265  
4266 =pod
4267  
4268 =item finished
4269  
4270 $h->finished;
4271  
4272 Returns true if the harness has been started and all child processes have
4273 finished (i.e. C<finish> has been called or the harness has run to
4274 completion). Returns false otherwise, including when the harness has not
4275 yet been started.
4276  
4277 Unlike L</result> and L</full_result>, C<finished> does not throw an
4278 exception when the harness has not yet run -- it simply returns false.
4279 This makes it safe to call at any point to test completion status.
4280  
4281 my $h = harness(\@cmd);
4282 $h->start;
4283 # ... do other work, pump $h as needed ...
4284 if ( $h->finished ) {
4285 print "Exit code: ", $h->result(0), "\n";
4286 }
4287  
4288 =cut
4289  
4290 sub finished {
4291 20 ▶ my IPC::Run $self = $_[0];
Subroutine finished: called CC=1 SCAR=0.0
Pod documented
4292 20 return $self->{STATE} == _finished;
4293 }
4294  
4295 ##
4296 ## Filter Scaffolding
4297 ##
4298 use vars (
4299 228 '$filter_op', ## The op running a filter chain right now
4300 '$filter_num', ## Which filter is being run right now.
4301 228 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
4302  
4303 ##
4304 ## A few filters and filter constructors
4305 ##
4306  
4307 =pod
4308  
4309 =back
4310  
4311 =back
4312  
4313 =head1 FILTERS
4314  
4315 These filters are used to modify input our output between a child
4316 process and a scalar or subroutine endpoint.
4317  
4318 =over
4319  
4320 =item binary
4321  
4322 run \@cmd, ">", binary, \$out;
4323 run \@cmd, ">", binary, \$out; ## Any TRUE value to enable
4324 run \@cmd, ">", binary 0, \$out; ## Any FALSE value to disable
4325  
4326 This is a constructor for a "binmode" "filter" that tells IPC::Run to keep
4327 the carriage returns that would ordinarily be edited out for you (binmode
4328 is usually off). This is not a real filter, but an option masquerading as
4329 a filter.
4330  
4331 It's not named "binmode" because you're likely to want to call Perl's binmode
4332 in programs that are piping binary data around.
4333  
4334 =cut
4335  
4336 sub binary(;$) {
4337 91 ▶ my $enable = @_ ? shift : 1;
Subroutine binary: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 26 65 91
4338 91 ▶ return bless sub { $enable }, "IPC::Run::binmode_pseudo_filter";
Subroutine __ANON__: called CC=1 SCAR=0.0
4339 }
4340  
4341 =pod
4342  
4343 =item new_chunker
4344  
4345 This breaks a stream of data in to chunks, based on an optional
4346 scalar or regular expression parameter. The default is the Perl
4347 input record separator in $/, which is a newline be default.
4348  
4349 run \@cmd, '>', new_chunker, \&lines_handler;
4350 run \@cmd, '>', new_chunker( "\r\n" ), \&lines_handler;
4351  
4352 Because this uses $/ by default, you should always pass in a parameter
4353 if you are worried about other code (modules, etc) modifying $/.
4354  
4355 If this filter is last in a filter chain that dumps in to a scalar,
4356 the scalar must be set to '' before a new chunk will be written to it.
4357  
4358 As an example of how a filter like this can be written, here's a
4359 chunker that splits on newlines:
4360  
4361 sub line_splitter {
4362 my ( $in_ref, $out_ref ) = @_;
4363  
4364 return 0 if length $$out_ref;
4365  
4366 return input_avail && do {
4367 while (1) {
4368 if ( $$in_ref =~ s/\A(.*?\n)// ) {
4369 $$out_ref .= $1;
4370 return 1;
4371 }
4372 my $hmm = get_more_input;
4373 unless ( defined $hmm ) {
4374 $$out_ref = $$in_ref;
4375 $$in_ref = '';
4376 return length $$out_ref ? 1 : 0;
4377 }
4378 return 0 if $hmm eq 0;
4379 }
4380 }
4381 };
4382  
4383 =cut
4384  
4385 sub new_chunker(;$) {
4386 5 ▶ my ($re) = @_;
Subroutine new_chunker: called CC=3 SCAR=11.0
Pod documented
4387 5 ▶ $re = $/ if _empty $re;
Branch: 1 branch
BranchTrueFalseTotal
if &_empty($re) 3 2 5
4388 5 ▶ $re = quotemeta($re) unless ref $re eq 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $re eq "Regexp" 4 1 5
4389 5 $re = qr/\A(.*?$re)/s;
4390  
4391 return sub {
4392 56 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=7 SCAR=19.7
4393  
4394 56 ▶ return 0 if length $$out_ref;
Branch: 1 branch
BranchTrueFalseTotal
if length $$out_ref 0 56 56
4395  
4396 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
4397 21 while (1) {
4398 29 ▶ if ( $$in_ref =~ s/$re// ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$in_ref =~ s/$re//) 17 12 29
4399 17 $$out_ref .= $1;
4400 17 return 1;
4401 }
4402 12 my $hmm = get_more_input;
4403 12 ▶ unless ( defined $hmm ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $hmm) 4 8 12
4404 4 $$out_ref = $$in_ref;
4405 4 $$in_ref = '';
4406 4 ▶ return length $$out_ref ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $$out_ref ? : 4 0 4
4407 }
4408 8 ▶ return 0 if $hmm eq 0;
Branch: 1 branch
BranchTrueFalseTotal
if $hmm eq 0 0 8 8
4409 }
4410 }
4411 5 };
4412 }
4413  
4414 =pod
4415  
4416 =item new_appender
4417  
4418 This appends a fixed string to each chunk of data read from the source
4419 scalar or sub. This might be useful if you're writing commands to a
4420 child process that always must end in a fixed string, like "\n":
4421  
4422 run( \@cmd,
4423 '<', new_appender( "\n" ), \&commands,
4424 );
4425  
4426 Here's a typical filter sub that might be created by new_appender():
4427  
4428 sub newline_appender {
4429 my ( $in_ref, $out_ref ) = @_;
4430  
4431 return input_avail && do {
4432 $$out_ref = join( '', $$out_ref, $$in_ref, "\n" );
4433 $$in_ref = '';
4434 1;
4435 }
4436 };
4437  
4438 =cut
4439  
4440 sub new_appender($) {
4441 1 ▶ my ($suffix) = @_;
Subroutine new_appender: called CC=2 SCAR=7.0
Pod documented
4442 1 ▶ croak "\$suffix undefined" unless defined $suffix;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $suffix 0 1 1
4443  
4444 return sub {
4445 10 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.0
4446  
4447 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
4448 3 $$out_ref = join( '', $$out_ref, $$in_ref, $suffix );
4449 3 $$in_ref = '';
4450 3 1;
4451 }
4452 1 };
4453 }
4454  
4455 =item new_string_source
4456  
4457 TODO: Needs confirmation. Was previously undocumented. in this module.
4458  
4459 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.
4460  
4461 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.
4462  
4463 =cut
4464  
4465 sub new_string_source {
4466 116 ▶ my $ref;
Subroutine new_string_source: called CC=3 SCAR=13.6
Pod documented
4467 116 ▶ if ( @_ > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) { } 0 116 116
4468 0 $ref = [@_],
4469 }
4470 else {
4471 116 $ref = shift;
4472 }
4473  
4474 return ref $ref eq 'SCALAR'
4475 ? sub {
4476 0 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
4477  
4478 return defined $$ref
4479 0 ▶ ? do {
Branch: 1 branch
BranchTrueFalseTotal
defined $$ref ? : 0 0 0
4480 0 $$out_ref .= $$ref;
4481 0 ▶ my $r = length $$ref ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $$ref ? : 0 0 0
4482 0 $$ref = undef;
4483 0 $r;
4484 }
4485 : undef;
4486 }
4487 : sub {
4488 998 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.0
4489  
4490 return @$ref
4491 998 ▶ ? do {
Branch: 1 branch
BranchTrueFalseTotal
@$ref ? : 361 637 998
4492 361 my $s = shift @$ref;
4493 361 $$out_ref .= $s;
4494 361 ▶ length $s ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $s ? : 129 232 361
4495 }
4496 : undef;
4497 }
4498 116 ▶}
Branch: 1 branch
BranchTrueFalseTotal
ref $ref eq 'SCALAR' ? : 0 116 116
4499  
4500 =item new_string_sink
4501  
4502 TODO: Needs confirmation. Was previously undocumented.
4503  
4504 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.
4505  
4506 =cut
4507  
4508 sub new_string_sink {
4509 116 ▶ my ($string_ref) = @_;
Subroutine new_string_sink: called CC=1 SCAR=0.0
Pod documented
4510  
4511 return sub {
4512 1212 ▶ my ( $in_ref, $out_ref ) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.0
4513  
4514 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
4515 400 $$string_ref .= $$in_ref;
4516 400 $$in_ref = '';
4517 400 1;
4518 }
4519 116 };
4520 }
4521  
4522 =pod
4523  
4524 =item io
4525  
4526 Takes a filename or filehandle, a redirection operator, optional filters,
4527 and a source or destination (depends on the redirection operator). Returns
4528 an IPC::Run::IO object suitable for harness()ing (including via start()
4529 or run()).
4530  
4531 This is shorthand for
4532  
4533  
4534 require IPC::Run::IO;
4535  
4536 ... IPC::Run::IO->new(...) ...
4537  
4538 =cut
4539  
4540 sub io {
4541 9 ▶ require IPC::Run::IO;
Subroutine io: called CC=1 SCAR=0.0
Pod documented
4542 9 IPC::Run::IO->new(@_);
4543 }
4544  
4545 =pod
4546  
4547 =item timer
4548  
4549 $h = start( \@cmd, \$in, \$out, $t = timer( 5 ) );
4550  
4551 pump $h until $out =~ /expected stuff/ || $t->is_expired;
4552  
4553 Instantiates a non-fatal timer. pump() returns once each time a timer
4554 expires. Has no direct effect on run(), but you can pass a subroutine
4555 to fire when the timer expires.
4556  
4557 See L</timeout> for building timers that throw exceptions on
4558 expiration.
4559  
4560 See L<IPC::Run::Timer/timer> for details.
4561  
4562 =cut
4563  
4564 # Doing the prototype suppresses 'only used once' on older perls.
4565 sub timer;
4566 228 *timer = \&IPC::Run::Timer::timer;
4567  
4568 =pod
4569  
4570 =item timeout
4571  
4572 $h = start( \@cmd, \$in, \$out, $t = timeout( 5 ) );
4573  
4574 pump $h until $out =~ /expected stuff/;
4575  
4576 Instantiates a timer that throws an exception when it expires.
4577 If you don't provide an exception, a default exception that matches
4578 /^IPC::Run: .*timed out/ is thrown by default. You can pass in your own
4579 exception scalar or reference:
4580  
4581 $h = start(
4582 \@cmd, \$in, \$out,
4583 $t = timeout( 5, exception => 'slowpoke' ),
4584 );
4585  
4586 or set the name used in debugging message and in the default exception
4587 string:
4588  
4589 $h = start(
4590 \@cmd, \$in, \$out,
4591 timeout( 50, name => 'process timer' ),
4592 $stall_timer = timeout( 5, name => 'stall timer' ),
4593 );
4594  
4595 pump $h until $out =~ /started/;
4596  
4597 $in = 'command 1';
4598 $stall_timer->start;
4599 pump $h until $out =~ /command 1 finished/;
4600  
4601 $in = 'command 2';
4602 $stall_timer->start;
4603 pump $h until $out =~ /command 2 finished/;
4604  
4605 $in = 'very slow command 3';
4606 $stall_timer->start( 10 );
4607 pump $h until $out =~ /command 3 finished/;
4608  
4609 $stall_timer->start( 5 );
4610 $in = 'command 4';
4611 pump $h until $out =~ /command 4 finished/;
4612  
4613 $stall_timer->reset; # Prevent restarting or expirng
4614 finish $h;
4615  
4616 See L</timer> for building non-fatal timers.
4617  
4618 See L<IPC::Run::Timer/timer> for details.
4619  
4620 =cut
4621  
4622 # Doing the prototype suppresses 'only used once' on older perls.
4623 sub timeout;
4624 228 *timeout = \&IPC::Run::Timer::timeout;
4625  
4626 =pod
4627  
4628 =back
4629  
4630 =head1 FILTER IMPLEMENTATION FUNCTIONS
4631  
4632 These functions are for use from within filters.
4633  
4634 =over
4635  
4636 =item input_avail
4637  
4638 Returns TRUE if input is available. If none is available, then
4639 &get_more_input is called and its result is returned.
4640  
4641 This is usually used in preference to &get_more_input so that the
4642 calling filter removes all data from the $in_ref before more data
4643 gets read in to $in_ref.
4644  
4645 C<input_avail> is usually used as part of a return expression:
4646  
4647 return input_avail && do {
4648 ## process the input just gotten
4649 1;
4650 };
4651  
4652 This technique allows input_avail to return the undef or 0 that a
4653 filter normally returns when there's no input to process. If a filter
4654 stores intermediate values, however, it will need to react to an
4655 undef:
4656  
4657 my $got = input_avail;
4658 if ( ! defined $got ) {
4659 ## No more input ever, flush internal buffers to $out_ref
4660 }
4661 return $got unless $got;
4662 ## Got some input, move as much as need be
4663 return 1 if $added_to_out_ref;
4664  
4665 =cut
4666  
4667 sub input_avail() {
4668 confess "Undefined FBUF ref for $filter_num+1"
4669 3109 ▶ unless defined $filter_op->{FBUFS}->[ $filter_num + 1 ];
Subroutine input_avail: called CC=3 SCAR=11.1
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless defined $IPC::Run::filter_op->{"FBUFS"}[$IPC::Run::filter_num + 1] 0 3109 3109
4670 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() 2466 643 3109
4671 }
4672  
4673 =pod
4674  
4675 =item get_more_input
4676  
4677 This is used to fetch more input in to the input variable. It returns
4678 undef if there will never be any more input, 0 if there is none now,
4679 but there might be in the future, and TRUE if more input was gotten.
4680  
4681 C<get_more_input> is usually used as part of a return expression,
4682 see L</input_avail> for more information.
4683  
4684 =cut
4685  
4686 ##
4687 ## Filter implementation interface
4688 ##
4689 sub get_more_input() {
4690 14423 ▶ ++$filter_num;
Subroutine get_more_input: called CC=3 SCAR=11.2
Pod documented
4691 14423 my $r = eval {
4692 confess "get_more_input() called and no more filters in chain"
4693 14423 ▶ unless defined $filter_op->{FILTERS}->[$filter_num];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $IPC::Run::filter_op->{"FILTERS"}[$IPC::Run::filter_num] 0 14423 14423
4694 $filter_op->{FILTERS}->[$filter_num]->(
4695 $filter_op->{FBUFS}->[ $filter_num + 1 ],
4696 14423 $filter_op->{FBUFS}->[$filter_num],
4697 ); # if defined ${$filter_op->{FBUFS}->[$filter_num+1]};
4698 };
4699 14423 --$filter_num;
4700 14423 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 14423 14423
4701 14423 return $r;
4702 }
4703  
4704 228 1;
4705  
4706 =pod
4707  
4708 =back
4709  
4710 =head1 TODO
4711  
4712 These will be addressed as needed and as time allows.
4713  
4714 Stall timeout.
4715  
4716 Expose a list of child process objects. When I do this,
4717 each child process is likely to be blessed into IPC::Run::Proc.
4718  
4719 $kid->abort(), $kid->kill(), $kid->signal( $num_or_name ).
4720  
4721 Write tests for /(full_)?results?/ subs.
4722  
4723 Currently, pump() and run() only work on systems where select() works on the
4724 filehandles returned by pipe(). This does *not* include ActiveState on Win32,
4725 although it does work on cygwin under Win32 (thought the tests whine a bit).
4726 I'd like to rectify that, suggestions and patches welcome.
4727  
4728 Likewise start() only fully works on fork()/exec() machines (well, just
4729 fork() if you only ever pass perl subs as subprocesses). There's
4730 some scaffolding for calling Open3::spawn_with_handles(), but that's
4731 untested, and not that useful with limited select().
4732  
4733 Support for C<\@sub_cmd> as an argument to a command which
4734 gets replaced with /dev/fd or the name of a temporary file containing foo's
4735 output. This is like <(sub_cmd ...) found in bash and csh (IIRC).
4736  
4737 Allow multiple harnesses to be combined as independent sets of processes
4738 in to one 'meta-harness'.
4739  
4740 Allow a harness to be passed in place of an \@cmd. This would allow
4741 multiple harnesses to be aggregated.
4742  
4743 Ability to add external file descriptors w/ filter chains and endpoints.
4744  
4745 Ability to add timeouts and timing generators (i.e. repeating timeouts).
4746  
4747 High resolution timeouts.
4748  
4749 =head1 Win32 LIMITATIONS
4750  
4751 =over
4752  
4753 =item argument-passing rules are program-specific
4754  
4755 Win32 programs receive all arguments in a single "command line" string.
4756 IPC::Run assembles this string so programs using L<standard command line parsing
4757 rules|https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args#parsing-c-command-line-arguments>
4758 will see an C<argv> that matches the array reference specifying the command.
4759 Some programs use different rules to parse their command line. Notable examples
4760 include F<cmd.exe>, F<cscript.exe>, and Cygwin programs called from non-Cygwin
4761 programs. Use L<IPC::Run::Win32Process> to call these and other nonstandard
4762 programs.
4763  
4764 =item batch files
4765  
4766 Properly escaping a batch file argument depends on how the script will use that
4767 argument, because some uses experience multiple levels of caret (escape
4768 character) removal. Avoid calling batch files with arguments, particularly when
4769 the argument values originate outside your program or contain non-alphanumeric
4770 characters. Perl scripts and PowerShell scripts are sound alternatives. If you
4771 do use batch file arguments, IPC::Run escapes them so the batch file can pass
4772 them, unquoted, to a program having standard command line parsing rules. If the
4773 batch file enables delayed environment variable expansion, it must disable that
4774 feature before expanding its arguments. For example, if F<foo.cmd> contains
4775 C<perl %*>, C<run ['foo.cmd', @list]> will create a Perl process in which
4776 C<@ARGV> matches C<@list>. Prepending a C<setlocal enabledelayedexpansion> line
4777 would make the batch file malfunction, silently. Another silent-malfunction
4778 example is C<run ['outer.bat', @list]> for F<outer.bat> containing C<foo.cmd
4779 %*>.
4780  
4781 =item Fails on Win9X
4782  
4783 If you want Win9X support, you'll have to debug it or fund me because I
4784 don't use that system any more. The Win32 subsysem has been extended to
4785 use temporary files in simple run() invocations and these may actually
4786 work on Win9X too, but I don't have time to work on it.
4787  
4788 =item May deadlock on Win2K (but not WinNT4 or WinXPPro)
4789  
4790 Spawning more than one subprocess on Win2K causes a deadlock I haven't
4791 figured out yet, but simple uses of run() often work. Passes all tests
4792 on WinXPPro and WinNT.
4793  
4794 =item no support yet for <pty< and >pty>
4795  
4796 These are likely to be implemented as "<" and ">" with binmode on, not
4797 sure.
4798  
4799 =item no support for file descriptors higher than 2 (stderr)
4800  
4801 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
4802 get the integer handle and pass it to the child process using the command
4803 line, environment, stdin, intermediary file, or other IPC mechanism. Then
4804 use that handle in the child (Win32API.pm provides ways to reconstitute
4805 Perl file handles from Win32 file handles).
4806  
4807 =item no support for subroutine subprocesses (CODE refs)
4808  
4809 Can't fork(), so the subroutines would have no context, and closures certainly
4810 have no meaning
4811  
4812 Perhaps with Win32 fork() emulation, this can be supported in a limited
4813 fashion, but there are other very serious problems with that: all parent
4814 fds get dup()ed in to the thread emulating the forked process, and that
4815 keeps the parent from being able to close all of the appropriate fds.
4816  
4817 =item no support for init => sub {} routines.
4818  
4819 Win32 processes are created from scratch, there is no way to do an init
4820 routine that will affect the running child. Some limited support might
4821 be implemented one day, do chdir() and %ENV changes can be made.
4822  
4823 =item signals
4824  
4825 Win32 does not fully support signals. signal() is likely to cause errors
4826 unless sending a signal that Perl emulates, and C<kill_kill()> is immediately
4827 fatal (there is no grace period).
4828  
4829 =item C<$?> cannot represent all Win32 exit codes
4830  
4831 Prefer C<full_result( ... )>, C<result( ... )>, or other IPC::Run methods.
4832  
4833 =item helper processes
4834  
4835 IPC::Run uses helper processes, one per redirected file, to adapt between the
4836 anonymous pipe connected to the child and the TCP socket connected to the
4837 parent. This is a waste of resources and will change in the future to either
4838 use threads (instead of helper processes) or a WaitForMultipleObjects call
4839 (instead of select). Please contact me if you can help with the
4840 WaitForMultipleObjects() approach; I haven't figured out how to get at it
4841 without C code.
4842  
4843 =item shutdown pause
4844  
4845 There seems to be a pause of up to 1 second between when a child program exits
4846 and the corresponding sockets indicate that they are closed in the parent.
4847 Not sure why.
4848  
4849 =item binmode
4850  
4851 binmode is not supported yet. The underpinnings are implemented, just ask
4852 if you need it.
4853  
4854 =item IPC::Run::IO
4855  
4856 IPC::Run::IO objects can be used on Unix to read or write arbitrary files. On
4857 Win32, they will need to use the same helper processes to adapt from
4858 non-select()able filehandles to select()able ones (or perhaps
4859 WaitForMultipleObjects() will work with them, not sure).
4860  
4861 =item startup race conditions
4862  
4863 There seems to be an occasional race condition between child process startup
4864 and pipe closings. It seems like if the child is not fully created by the time
4865 CreateProcess returns and we close the TCP socket being handed to it, the
4866 parent socket can also get closed. This is seen with the Win32 pumper
4867 applications, not the "real" child process being spawned.
4868  
4869 I assume this is because the kernel hasn't gotten around to incrementing the
4870 reference count on the child's end (since the child was slow in starting), so
4871 the parent's closing of the child end causes the socket to be closed, thus
4872 closing the parent socket.
4873  
4874 Being a race condition, it's hard to reproduce, but I encountered it while
4875 testing this code on a drive share to a samba box. In this case, it takes
4876 t/run.t a long time to spawn its child processes (the parent hangs in the
4877 first select for several seconds until the child emits any debugging output).
4878  
4879 I have not seen it on local drives, and can't reproduce it at will,
4880 unfortunately. The symptom is a "bad file descriptor in select()" error, and,
4881 by turning on debugging, it's possible to see that select() is being called on
4882 a no longer open file descriptor that was returned from the _socket() routine
4883 in Win32Helper. There's a new confess() that checks for this ("PARENT_HANDLE
4884 no longer open"), but I haven't been able to reproduce it (typically).
4885  
4886 =back
4887  
4888 =head1 LIMITATIONS
4889  
4890 On Unix, requires a system that supports C<waitpid( $pid, WNOHANG )> so
4891 it can tell if a child process is still running.
4892  
4893 PTYs don't seem to be non-blocking on some versions of Solaris. Here's a
4894 test script contributed by Borislav Deianov <borislav@ensim.com> to see
4895 if you have the problem. If it dies, you have the problem.
4896  
4897 #!/usr/bin/perl
4898  
4899 use IPC::Run qw(run);
4900 use Fcntl;
4901 use IO::Pty;
4902  
4903 sub makecmd {
4904 return ['perl', '-e',
4905 '<STDIN>, print "\n" x '.$_[0].'; while(<STDIN>){last if /end/}'];
4906 }
4907  
4908 #pipe R, W;
4909 #fcntl(W, F_SETFL, O_NONBLOCK);
4910 #while (syswrite(W, "\n", 1)) { $pipebuf++ };
4911 #print "pipe buffer size is $pipebuf\n";
4912 my $pipebuf=4096;
4913 my $in = "\n" x ($pipebuf * 2) . "end\n";
4914 my $out;
4915  
4916 $SIG{ALRM} = sub { die "Never completed!\n" };
4917  
4918 print "reading from scalar via pipe...";
4919 alarm( 2 );
4920 run(makecmd($pipebuf * 2), '<', \$in, '>', \$out);
4921 alarm( 0 );
4922 print "done\n";
4923  
4924 print "reading from code via pipe... ";
4925 alarm( 2 );
4926 run(makecmd($pipebuf * 3), '<', sub { $t = $in; undef $in; $t}, '>', \$out);
4927 alarm( 0 );
4928 print "done\n";
4929  
4930 $pty = IO::Pty->new();
4931 $pty->blocking(0);
4932 $slave = $pty->slave();
4933 while ($pty->syswrite("\n", 1)) { $ptybuf++ };
4934 print "pty buffer size is $ptybuf\n";
4935 $in = "\n" x ($ptybuf * 3) . "end\n";
4936  
4937 print "reading via pty... ";
4938 alarm( 2 );
4939 run(makecmd($ptybuf * 3), '<pty<', \$in, '>', \$out);
4940 alarm(0);
4941 print "done\n";
4942  
4943 IO::Pty version 1.21 and later added a C<DESTROY> method that automatically
4944 closes the cached slave pty handle when the master is destroyed. IPC::Run
4945 works around this by detaching the slave before closing the master in the
4946 child process; no user action is required.
4947  
4948 No support for ';', '&&', '||', '{ ... }', etc: use perl's, since run()
4949 returns TRUE when the command exits with a 0 result code.
4950  
4951 Does not provide shell-like string interpolation.
4952  
4953 No support for C<cd> or C<export>: do C<cd> in an init() sub.
4954  
4955 For setting environment variables in the child process without affecting the
4956 parent, use the C<env> option (a hash reference of key/value pairs):
4957  
4958 run(
4959 \cmd,
4960 ...
4961 env => { FOO => 'BAR', BAZ => 'QUX' }
4962 );
4963  
4964 The C<env> variables are applied in the child process before any C<init> subs
4965 run, so C<init> can still override individual variables if needed. The parent
4966 process C<%ENV> is not modified.
4967  
4968 Alternatively, use an C<init> sub for more complex setup:
4969  
4970 run(
4971 \cmd,
4972 ...
4973 init => sub {
4974 chdir $dir or die $!;
4975 $ENV{FOO}='BAR'
4976 }
4977 );
4978  
4979 Timeout calculation does not allow absolute times, or specification of
4980 days, months, etc.
4981  
4982 B<WARNING:> Function coprocesses (C<run \&foo, ...>) suffer from two
4983 limitations. The first is that it is difficult to close all filehandles the
4984 child inherits from the parent, since there is no way to scan all open
4985 FILEHANDLEs in Perl and it is both painful and a bit dangerous to close all open
4986 file descriptors with C<POSIX::close()>. Painful because we can't tell which
4987 fds are open at the POSIX level, either, so we'd have to scan all possible fds
4988 and close any that we don't want open (normally C<exec()> closes any
4989 non-inheritable but we don't C<exec()> for &sub processes).
4990  
4991 The second problem is that Perl's DESTROY subs and other on-exit cleanup gets
4992 run in the child process. If objects are instantiated in the parent before the
4993 child is forked, the DESTROY will get run once in the parent and once in
4994 the child. When coprocess subs exit, POSIX::_exit is called to work around this,
4995 but it means that objects that are still referred to at that time are not
4996 cleaned up. So setting package vars or closure vars to point to objects that
4997 rely on DESTROY to affect things outside the process (files, etc), will
4998 lead to bugs.
4999  
5000 I goofed on the syntax: "<pipe" vs. "<pty<" and ">filename" are both
5001 oddities.
5002  
5003 =head1 TODO
5004  
5005 =over
5006  
5007 =item Allow one harness to "adopt" another:
5008  
5009 $new_h = harness \@cmd2;
5010 $h->adopt( $new_h );
5011  
5012 =item Close all filehandles not explicitly marked to stay open.
5013  
5014 The problem with this one is that there's no good way to scan all open
5015 FILEHANDLEs in Perl, yet you don't want child processes inheriting handles
5016 willy-nilly.
5017  
5018 =back
5019  
5020 =head1 INSPIRATION
5021  
5022 Well, select() and waitpid() badly needed wrapping, and open3() isn't
5023 open-minded enough for me.
5024  
5025 The shell-like API inspired by a message Russ Allbery sent to perl5-porters,
5026 which included:
5027  
5028 I've thought for some time that it would be
5029 nice to have a module that could handle full Bourne shell pipe syntax
5030 internally, with fork and exec, without ever invoking a shell. Something
5031 that you could give things like:
5032  
5033 pipeopen (PIPE, [ qw/cat file/ ], '|', [ 'analyze', @args ], '>&3');
5034  
5035 Message ylln51p2b6.fsf@windlord.stanford.edu, on 2000/02/04.
5036  
5037 =head1 SUPPORT
5038  
5039 Bugs should always be submitted via the GitHub bug tracker
5040  
5041 L<https://github.com/cpan-authors/IPC-Run/issues>
5042  
5043 =head1 AUTHORS
5044  
5045 Adam Kennedy <adamk@cpan.org>
5046  
5047 Barrie Slaymaker <barries@slaysys.com>
5048  
5049 =head1 COPYRIGHT
5050  
5051 Some parts copyright 2008 - 2009 Adam Kennedy.
5052  
5053 Copyright 1999 Barrie Slaymaker.
5054  
5055 You may distribute under the terms of either the GNU General Public
5056 License or the Artistic License, as specified in the README file.
5057  
5058 =cut
« blib/lib/IPC/Run/Win32Helper.pm ↑ Summary blib/lib/IPC/Run/Win32IO.pm »