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