File Coverage

blib/lib/IO/Async/Process.pm
Criterion Covered Total %
statement 219 224 97.7
branch 121 152 79.6
condition 28 38 73.6
subroutine 36 36 100.0
pod 16 17 94.1
total 420 467 89.9


line stmt bran cond sub pod time code
1             # You may distribute under the terms of either the GNU General Public License
2             # or the Artistic License (the same terms as Perl itself)
3             #
4             # (C) Paul Evans, 2011-2018 -- leonerd@leonerd.org.uk
5              
6             package IO::Async::Process;
7              
8 41     41   879434 use strict;
  41         88  
  41         1115  
9 41     41   183 use warnings;
  41         59  
  41         1034  
10 41     41   209 use base qw( IO::Async::Notifier );
  41         76  
  41         14291  
11              
12             our $VERSION = '0.802';
13              
14 41     41   283 use Carp;
  41         72  
  41         2447  
15              
16 41     41   7403 use Socket qw( SOCK_STREAM );
  41         47308  
  41         3159  
17              
18 41     41   232 use Future;
  41         82  
  41         855  
19              
20 41     41   6193 use IO::Async::OS;
  41         75  
  41         18282  
21              
22             =head1 NAME
23              
24             C - start and manage a child process
25              
26             =head1 SYNOPSIS
27              
28             use IO::Async::Process;
29              
30             use IO::Async::Loop;
31             my $loop = IO::Async::Loop->new;
32              
33             my $process = IO::Async::Process->new(
34             command => [ "tr", "a-z", "n-za-m" ],
35             stdin => {
36             from => "hello world\n",
37             },
38             stdout => {
39             on_read => sub {
40             my ( $stream, $buffref ) = @_;
41             while( $$buffref =~ s/^(.*)\n// ) {
42             print "Rot13 of 'hello world' is '$1'\n";
43             }
44              
45             return 0;
46             },
47             },
48              
49             on_finish => sub {
50             $loop->stop;
51             },
52             );
53              
54             $loop->add( $process );
55              
56             $loop->run;
57              
58             Also accessible via the L method:
59              
60             $loop->open_process(
61             command => [ "/bin/ping", "-c4", "some.host" ],
62              
63             stdout => {
64             on_read => sub {
65             my ( $stream, $buffref, $eof ) = @_;
66             while( $$buffref =~ s/^(.*)\n// ) {
67             print "PING wrote: $1\n";
68             }
69             return 0;
70             },
71             },
72              
73             on_finish => sub {
74             my $process = shift;
75             my ( $exitcode ) = @_;
76             my $status = ( $exitcode >> 8 );
77             ...
78             },
79             );
80              
81             =head1 DESCRIPTION
82              
83             This subclass of L starts a child process, and invokes a
84             callback when it exits. The child process can either execute a given block of
85             code (via C), or a command.
86              
87             =cut
88              
89             =head1 EVENTS
90              
91             The following events are invoked, either using subclass methods or CODE
92             references in parameters:
93              
94             =head2 on_finish $exitcode
95              
96             Invoked after the process has exited by normal means (i.e. an C
97             syscall from a process, or Cing from the code block), and has closed
98             all its file descriptors.
99              
100             =head2 on_exception $exception, $errno, $exitcode
101              
102             Invoked when the process exits by an exception from C, or by failing to
103             C the given command. C<$errno> will be a dualvar, containing both
104             number and string values. After a successful C call, this condition
105             can no longer happen.
106              
107             Note that this has a different name and a different argument order from
108             C<< Loop->open_process >>'s C.
109              
110             If this is not provided and the process exits with an exception, then
111             C is invoked instead, being passed just the exit code.
112              
113             Since this is just the results of the underlying C<< $loop->spawn_child >>
114             C handler in a different order it is possible that the C<$exception>
115             field will be an empty string. It will however always be defined. This can be
116             used to distinguish the two cases:
117              
118             on_exception => sub {
119             my $self = shift;
120             my ( $exception, $errno, $exitcode ) = @_;
121              
122             if( length $exception ) {
123             print STDERR "The process died with the exception $exception " .
124             "(errno was $errno)\n";
125             }
126             elsif( ( my $status = W_EXITSTATUS($exitcode) ) == 255 ) {
127             print STDERR "The process failed to exec() - $errno\n";
128             }
129             else {
130             print STDERR "The process exited with exit status $status\n";
131             }
132             }
133              
134             =cut
135              
136             =head1 CONSTRUCTOR
137              
138             =cut
139              
140             =head2 new
141              
142             $process = IO::Async::Process->new( %args )
143              
144             Constructs a new C object and returns it.
145              
146             Once constructed, the C will need to be added to the C before
147             the child process is started.
148              
149             =cut
150              
151             sub _init
152             {
153 275     275   982 my $self = shift;
154 275         1539 $self->SUPER::_init( @_ );
155              
156 275         958 $self->{to_close} = {};
157 275         867 $self->{finish_futures} = [];
158             }
159              
160             =head1 PARAMETERS
161              
162             The following named parameters may be passed to C or C:
163              
164             =head2 on_finish => CODE
165              
166             =head2 on_exception => CODE
167              
168             CODE reference for the event handlers.
169              
170             Once the C continuation has been invoked, the C
171             object is removed from the containing L object.
172              
173             The following parameters may be passed to C, or to C before
174             the process has been started (i.e. before it has been added to the C).
175             Once the process is running these cannot be changed.
176              
177             =head2 command => ARRAY or STRING
178              
179             Either a reference to an array containing the command and its arguments, or a
180             plain string containing the command. This value is passed into perl's
181             C function.
182              
183             =head2 code => CODE
184              
185             A block of code to execute in the child process. It will be called in scalar
186             context inside an C block.
187              
188             =head2 setup => ARRAY
189              
190             Optional reference to an array to pass to the underlying C
191             C method.
192              
193             =head2 fdI => HASH
194              
195             A hash describing how to set up file descriptor I. The hash may contain the
196             following keys:
197              
198             =over 4
199              
200             =item via => STRING
201              
202             Configures how this file descriptor will be configured for the child process.
203             Must be given one of the following mode names:
204              
205             =over 4
206              
207             =item pipe_read
208              
209             The child will be given the writing end of a C; the parent may read
210             from the other.
211              
212             =item pipe_write
213              
214             The child will be given the reading end of a C; the parent may write
215             to the other. Since an EOF condition of this kind of handle cannot reliably be
216             detected, C will not wait for this type of pipe to be closed.
217              
218             =item pipe_rdwr
219              
220             Only valid on the C filehandle. The child will be given the reading end
221             of one C on STDIN and the writing end of another on STDOUT. A single
222             Stream object will be created in the parent configured for both filehandles.
223              
224             =item socketpair
225              
226             The child will be given one end of a C; the parent will be
227             given the other. The family of this socket may be given by the extra key
228             called C; defaulting to C. The socktype of this socket may be
229             given by the extra key called C; defaulting to C. If the
230             type is not C then a L object will be
231             constructed for the parent side of the handle, rather than
232             L.
233              
234             =back
235              
236             Once the filehandle is set up, the C method (or its shortcuts of C,
237             C or C) may be used to access the
238             L-subclassed object wrapped around it.
239              
240             The value of this argument is implied by any of the following alternatives.
241              
242             =item on_read => CODE
243              
244             The child will be given the writing end of a pipe. The reading end will be
245             wrapped by an L using this C callback function.
246              
247             =item into => SCALAR
248              
249             The child will be given the writing end of a pipe. The referenced scalar will
250             be filled by data read from the child process. This data may not be available
251             until the pipe has been closed by the child.
252              
253             =item from => STRING
254              
255             The child will be given the reading end of a pipe. The string given by the
256             C parameter will be written to the child. When all of the data has been
257             written the pipe will be closed.
258              
259             =item prefork => CODE
260              
261             Only valid for handles with a C of C. The code block runs
262             after the C is created, but before the child is forked. This
263             is handy for when you adjust both ends of the created socket (for example, to
264             use C) from the controlling parent, before the child code runs.
265             The arguments passed in are the L objects for the parent and child
266             ends of the socket.
267              
268             $prefork->( $localfd, $childfd )
269              
270             =back
271              
272             =head2 stdin => ...
273              
274             =head2 stdout => ...
275              
276             =head2 stderr => ...
277              
278             Shortcuts for C, C and C respectively.
279              
280             =head2 stdio => ...
281              
282             Special filehandle to affect STDIN and STDOUT at the same time. This
283             filehandle supports being configured for both reading and writing at the same
284             time.
285              
286             =cut
287              
288             sub configure
289             {
290 275     275 1 599 my $self = shift;
291 275         1592 my %params = @_;
292              
293 275         852 foreach (qw( on_finish on_exception )) {
294 550 100       1934 $self->{$_} = delete $params{$_} if exists $params{$_};
295             }
296              
297             # All these parameters can only be configured while the process isn't
298             # running
299 275         740 my %setup_params;
300 275         1337 foreach (qw( code command setup stdin stdout stderr stdio ), grep { m/^fd\d+$/ } keys %params ) {
  821         2906  
301 1933 100       4245 $setup_params{$_} = delete $params{$_} if exists $params{$_};
302             }
303              
304 275 50       1617 if( $self->is_running ) {
305 0 0       0 keys %setup_params and croak "Cannot configure a running Process with " . join ", ", keys %setup_params;
306             }
307              
308             defined( exists $setup_params{code} ? $setup_params{code} : $self->{code} ) +
309 275 100       1969 defined( exists $setup_params{command} ? $setup_params{command} : $self->{command} ) <= 1 or
    100          
    50          
310             croak "Cannot have both 'code' and 'command'";
311              
312 275         627 foreach (qw( code command setup )) {
313 825 100       2019 $self->{$_} = delete $setup_params{$_} if exists $setup_params{$_};
314             }
315              
316 275 100       905 $self->configure_fd( 0, %{ delete $setup_params{stdin} } ) if $setup_params{stdin};
  32         357  
317 275 100       840 $self->configure_fd( 1, %{ delete $setup_params{stdout} } ) if $setup_params{stdout};
  132         893  
318 275 100       1051 $self->configure_fd( 2, %{ delete $setup_params{stderr} } ) if $setup_params{stderr};
  53         397  
319              
320 275 100       680 $self->configure_fd( 'io', %{ delete $setup_params{stdio} } ) if $setup_params{stdio};
  9         92  
321              
322             # All the rest are fd\d+
323 275         724 foreach ( keys %setup_params ) {
324 8 50       92 my ( $fd ) = m/^fd(\d+)$/ or croak "Expected 'fd\\d+'";
325 8         32 $self->configure_fd( $fd, %{ $setup_params{$_} } );
  8         96  
326             }
327              
328 275         1202 $self->SUPER::configure( %params );
329             }
330              
331             # These are from the perspective of the parent
332 41     41   285 use constant FD_VIA_PIPEREAD => 1;
  41         112  
  41         2238  
333 41     41   261 use constant FD_VIA_PIPEWRITE => 2;
  41         90  
  41         1912  
334 41     41   211 use constant FD_VIA_PIPERDWR => 3; # Only valid for stdio pseudo-fd
  41         86  
  41         1857  
335 41     41   249 use constant FD_VIA_SOCKETPAIR => 4;
  41         87  
  41         85644  
336              
337             my %via_names = (
338             pipe_read => FD_VIA_PIPEREAD,
339             pipe_write => FD_VIA_PIPEWRITE,
340             pipe_rdwr => FD_VIA_PIPERDWR,
341             socketpair => FD_VIA_SOCKETPAIR,
342             );
343              
344             sub configure_fd
345             {
346 234     234 0 508 my $self = shift;
347 234         692 my ( $fd, %args ) = @_;
348              
349 234 50       766 $self->is_running and croak "Cannot configure fd $fd in a running Process";
350              
351 234 100 100     2158 if( $fd eq "io" ) {
    100          
352 9   33     97 exists $self->{fd_opts}{$_} and croak "Cannot configure stdio since fd$_ is already defined" for 0 .. 1;
353             }
354             elsif( $fd == 0 or $fd == 1 ) {
355 172 50       691 exists $self->{fd_opts}{io} and croak "Cannot configure fd$fd since stdio is already defined";
356             }
357              
358 234   50     2074 my $opts = $self->{fd_opts}{$fd} ||= {};
359 234         593 my $via = $opts->{via};
360              
361 234         396 my ( $wants_read, $wants_write );
362              
363 234 100       849 if( my $via_name = delete $args{via} ) {
364 32 50       93 defined $via and
365             croak "Cannot change the 'via' mode of fd$fd now that it is already configured";
366              
367 32 50       144 $via = $via_names{$via_name} or
368             croak "Unrecognised 'via' name of '$via_name'";
369             }
370              
371 234 100       1525 if( my $on_read = delete $args{on_read} ) {
    100          
372 10         40 $opts->{handle}{on_read} = $on_read;
373              
374 10         30 $wants_read++;
375             }
376             elsif( my $into = delete $args{into} ) {
377             $opts->{handle}{on_read} = sub {
378 236     236   1145 my ( undef, $buffref, $eof ) = @_;
379 236 100       1004 $$into .= $$buffref if $eof;
380 236         906 return 0;
381 171         1049 };
382              
383 171         394 $wants_read++;
384             }
385              
386 234 100       693 if( defined( my $from = delete $args{from} ) ) {
387 23         102 $opts->{from} = $from;
388              
389 23         88 $wants_write++;
390             }
391              
392 234 100 100     865 if( defined $via and $via == FD_VIA_SOCKETPAIR ) {
393 4         33 $self->{fd_opts}{$fd}{$_} = delete $args{$_} for qw( family socktype prefork );
394             }
395              
396 234 50       578 keys %args and croak "Unexpected extra keys for fd $fd - " . join ", ", keys %args;
397              
398 234 100 66     1132 if( !defined $via ) {
    100          
    100          
    50          
399 202 100 100     1339 $via = FD_VIA_PIPEREAD if $wants_read and !$wants_write;
400 202 100 66     919 $via = FD_VIA_PIPEWRITE if !$wants_read and $wants_write;
401 202 100 100     1098 $via = FD_VIA_PIPERDWR if $wants_read and $wants_write;
402             }
403             elsif( $via == FD_VIA_PIPEREAD ) {
404 10 50       20 $wants_write and $via = FD_VIA_PIPERDWR;
405             }
406             elsif( $via == FD_VIA_PIPEWRITE ) {
407 15 50       117 $wants_read and $via = FD_VIA_PIPERDWR;
408             }
409             elsif( $via == FD_VIA_PIPERDWR or $via == FD_VIA_SOCKETPAIR ) {
410             # Fine
411             }
412             else {
413 0         0 die "Need to check fd_via{$fd}\n";
414             }
415              
416 234 50 66     936 $via == FD_VIA_PIPERDWR and $fd ne "io" and
417             croak "Cannot both read and write simultaneously on fd$fd";
418              
419 234 50       1225 defined $via and $opts->{via} = $via;
420             }
421              
422             sub _prepare_fds
423             {
424 274     274   474 my $self = shift;
425 274         9967 my ( $loop ) = @_;
426              
427 274         541 my $fd_handle = $self->{fd_handle};
428 274         453 my $fd_opts = $self->{fd_opts};
429              
430 274         993 my $finish_futures = $self->{finish_futures};
431              
432 274         423 my @setup;
433              
434 274         1712 foreach my $fd ( keys %$fd_opts ) {
435 234         510 my $opts = $fd_opts->{$fd};
436 234         584 my $via = $opts->{via};
437              
438 234         640 my $handle = $self->fd( $fd );
439              
440 234 100       1351 my $key = $fd eq "io" ? "stdio" : "fd$fd";
441 234         438 my $write_only;
442              
443 234 100       749 if( $via == FD_VIA_PIPEREAD ) {
    100          
    100          
    50          
444 189 50       2660 my ( $myfd, $childfd ) = IO::Async::OS->pipepair or croak "Unable to pipe() - $!";
445 189         2013 $myfd->blocking( 0 );
446              
447 189         1324 $handle->configure( read_handle => $myfd );
448              
449 189         872 push @setup, $key => [ dup => $childfd ];
450 189         742 $self->{to_close}{$childfd->fileno} = $childfd;
451             }
452             elsif( $via == FD_VIA_PIPEWRITE ) {
453 36 50       570 my ( $childfd, $myfd ) = IO::Async::OS->pipepair or croak "Unable to pipe() - $!";
454 36         368 $myfd->blocking( 0 );
455 36         103 $write_only++;
456              
457 36         198 $handle->configure( write_handle => $myfd );
458              
459 36         298 push @setup, $key => [ dup => $childfd ];
460 36         219 $self->{to_close}{$childfd->fileno} = $childfd;
461             }
462             elsif( $via == FD_VIA_PIPERDWR ) {
463 5 50       36 $key eq "stdio" or croak "Oops - should only be FD_VIA_PIPERDWR on stdio";
464             # Can't use pipequad here for now because we need separate FDs so we
465             # can ->close them properly
466 5 50       106 my ( $myread, $childwrite ) = IO::Async::OS->pipepair or croak "Unable to pipe() - $!";
467 5 50       54 my ( $childread, $mywrite ) = IO::Async::OS->pipepair or croak "Unable to pipe() - $!";
468 5         78 $_->blocking( 0 ) for $myread, $mywrite;
469              
470 5         26 $handle->configure( read_handle => $myread, write_handle => $mywrite );
471              
472 5         45 push @setup, stdin => [ dup => $childread ], stdout => [ dup => $childwrite ];
473 5         33 $self->{to_close}{$childread->fileno} = $childread;
474 5         53 $self->{to_close}{$childwrite->fileno} = $childwrite;
475             }
476             elsif( $via == FD_VIA_SOCKETPAIR ) {
477 4 50       101 my ( $myfd, $childfd ) = IO::Async::OS->socketpair( $opts->{family}, $opts->{socktype} ) or croak "Unable to socketpair() - $!";
478 4         38 $myfd->blocking( 0 );
479              
480 4 100       78 $opts->{prefork}->( $myfd, $childfd ) if $opts->{prefork};
481              
482 4         73 $handle->configure( handle => $myfd );
483              
484 4 50       30 if( $key eq "stdio" ) {
485 4         19 push @setup, stdin => [ dup => $childfd ], stdout => [ dup => $childfd ];
486             }
487             else {
488 0         0 push @setup, $key => [ dup => $childfd ];
489             }
490 4         18 $self->{to_close}{$childfd->fileno} = $childfd;
491             }
492             else {
493 0         0 croak "Unsure what to do with fd_via==$via";
494             }
495              
496 234         2108 $self->add_child( $handle );
497              
498 234 100       491 unless( $write_only ) {
499 198         845 push @$finish_futures, $handle->new_close_future;
500             }
501             }
502              
503 274         1028 return @setup;
504             }
505              
506             sub _add_to_loop
507             {
508 275     275   541 my $self = shift;
509 275         647 my ( $loop ) = @_;
510              
511             $self->{code} or $self->{command} or
512 275 50 66     1779 croak "Require either 'code' or 'command' in $self";
513              
514 275 100       1107 $self->can_event( "on_finish" ) or
515             croak "Expected either an on_finish callback or to be able to ->on_finish";
516              
517 274         492 my @setup;
518 274 100       658 push @setup, @{ $self->{setup} } if $self->{setup};
  77         254  
519              
520 274         1243 push @setup, $self->_prepare_fds( $loop );
521              
522 274         622 my $finish_futures = delete $self->{finish_futures};
523              
524 274         469 my ( $exitcode, $dollarbang, $dollarat );
525 274         856 push @$finish_futures, my $exit_future = $loop->new_future;
526              
527             $self->{pid} = $loop->spawn_child(
528             code => $self->{code},
529             command => $self->{command},
530              
531             setup => \@setup,
532              
533             on_exit => $self->_capture_weakself( sub {
534 237     237   1773 ( my $self, undef, $exitcode, $dollarbang, $dollarat ) = @_;
535              
536 237 100       1547 $self->debug_printf( "EXIT status=0x%04x", $exitcode ) if $self;
537 237 100       1652 $exit_future->done unless $exit_future->is_cancelled;
538 274         2405 } ),
539             );
540 248         5128 $self->{running} = 1;
541              
542 248         2895 $self->SUPER::_add_to_loop( @_ );
543              
544 248         2619 $_->close for values %{ delete $self->{to_close} };
  248         5706  
545              
546 248         5394 my $is_code = defined $self->{code};
547              
548 248         4082 my $f = $self->finish_future;
549              
550             $self->{_finish_future} = Future->needs_all( @$finish_futures )
551             ->on_done( $self->_capture_weakself( sub {
552 190 50   190   631 my $self = shift or return;
553              
554 190 100       1953 $self->debug_printf( "FINISH status=0x%04x%s", $exitcode,
    100          
555             join " ", '', ( $dollarbang ? '$!' : '' ), ( $dollarat ? '$@' : '' )
556             );
557              
558 190         1124 $self->{exitcode} = $exitcode;
559 190         804 $self->{dollarbang} = $dollarbang;
560 190         729 $self->{dollarat} = $dollarat;
561              
562 190         401 undef $self->{running};
563              
564 190 100       744 if( $is_code ? $dollarat eq "" : $dollarbang == 0 ) {
    100          
565 177         781 $self->invoke_event( on_finish => $exitcode );
566             }
567             else {
568 13 100       255 $self->maybe_invoke_event( on_exception => $dollarat, $dollarbang, $exitcode ) or
569             # Don't have a way to report dollarbang/dollarat
570             $self->invoke_event( on_finish => $exitcode );
571             }
572              
573 190         4266 $f->done( $exitcode );
574              
575 190         7008 $self->remove_from_parent;
576 248         7190 } ),
577             );
578             }
579              
580             sub DESTROY
581             {
582 234     234   73240 my $self = shift;
583 234 100       2330 $self->{_finish_future}->cancel if $self->{_finish_future};
584             }
585              
586             sub notifier_name
587             {
588 12     12 1 2124 my $self = shift;
589 12 50       96 if( length( my $name = $self->SUPER::notifier_name ) ) {
590 0         0 return $name;
591             }
592              
593 12 100       28 return "nopid" unless my $pid = $self->pid;
594 8 100       16 return "[$pid]" unless $self->is_running;
595 4         24 return "$pid";
596             }
597              
598             =head1 METHODS
599              
600             =cut
601              
602             =head2 finish_future
603              
604             $f = $process->finish_future
605              
606             I
607              
608             Returns a L that completes when the process finishes. It will yield
609             the exit code from the process.
610              
611             =cut
612              
613             sub finish_future
614             {
615 256     256 1 846 my $self = shift;
616 256   66     5589 return $self->{finish_future} //= $self->loop->new_future;
617             }
618              
619             =head2 pid
620              
621             $pid = $process->pid
622              
623             Returns the process ID of the process, if it has been started, or C if
624             not. Its value is preserved after the process exits, so it may be inspected
625             during the C or C events.
626              
627             =cut
628              
629             sub pid
630             {
631 133     133 1 498 my $self = shift;
632 133         2010 return $self->{pid};
633             }
634              
635             =head2 kill
636              
637             $process->kill( $signal )
638              
639             Sends a signal to the process
640              
641             =cut
642              
643             sub kill
644             {
645 4     4 1 73 my $self = shift;
646 4         34 my ( $signal ) = @_;
647              
648 4 50       62 kill $signal, $self->pid or croak "Cannot kill() - $!";
649             }
650              
651             =head2 is_running
652              
653             $running = $process->is_running
654              
655             Returns true if the Process has been started, and has not yet finished.
656              
657             =cut
658              
659             sub is_running
660             {
661 926     926 1 3409 my $self = shift;
662 926         5566 return $self->{running};
663             }
664              
665             =head2 is_exited
666              
667             $exited = $process->is_exited
668              
669             Returns true if the Process has finished running, and finished due to normal
670             C.
671              
672             =cut
673              
674             sub is_exited
675             {
676 102     102 1 16029 my $self = shift;
677 102 50       1673 return defined $self->{exitcode} ? ( $self->{exitcode} & 0x7f ) == 0 : undef;
678             }
679              
680             =head2 exitstatus
681              
682             $status = $process->exitstatus
683              
684             If the process exited due to normal C, returns the value that was
685             passed to C. Otherwise, returns C.
686              
687             =cut
688              
689             sub exitstatus
690             {
691 102     102 1 336 my $self = shift;
692 102 50       1287 return defined $self->{exitcode} ? ( $self->{exitcode} >> 8 ) : undef;
693             }
694              
695             =head2 exception
696              
697             $exception = $process->exception
698              
699             If the process exited due to an exception, returns the exception that was
700             thrown. Otherwise, returns C.
701              
702             =cut
703              
704             sub exception
705             {
706 9     9 1 36 my $self = shift;
707 9         81 return $self->{dollarat};
708             }
709              
710             =head2 errno
711              
712             $errno = $process->errno
713              
714             If the process exited due to an exception, returns the numerical value of
715             C<$!> at the time the exception was thrown. Otherwise, returns C.
716              
717             =cut
718              
719             sub errno
720             {
721 1     1 1 7 my $self = shift;
722 1         19 return $self->{dollarbang}+0;
723             }
724              
725             =head2 errstr
726              
727             $errstr = $process->errstr
728              
729             If the process exited due to an exception, returns the string value of
730             C<$!> at the time the exception was thrown. Otherwise, returns C.
731              
732             =cut
733              
734             sub errstr
735             {
736 1     1 1 9 my $self = shift;
737 1         12 return $self->{dollarbang}."";
738             }
739              
740             =head2 fd
741              
742             $stream = $process->fd( $fd )
743              
744             Returns the L or L associated with the
745             given FD number. This must have been set up by a C argument prior
746             to adding the C object to the C.
747              
748             The returned object have its read or write handle set to the other end of a
749             pipe or socket connected to that FD number in the child process. Typically,
750             this will be used to call the C method on, to write more data into the
751             child, or to set an C handler to read data out of the child.
752              
753             The C event for these streams must not be changed, or it will break
754             the close detection used by the C object and the C event
755             will not be invoked.
756              
757             =cut
758              
759             sub fd
760             {
761 437     437 1 731 my $self = shift;
762 437         1099 my ( $fd ) = @_;
763              
764 437   66     3318 return $self->{fd_handle}{$fd} ||= do {
765 234 50       807 my $opts = $self->{fd_opts}{$fd} or
766             croak "$self does not have an fd Stream for $fd";
767              
768 234         439 my $handle_class;
769 234 100 66     851 if( defined $opts->{socktype} && IO::Async::OS->getsocktypebyname( $opts->{socktype} ) != SOCK_STREAM ) {
770 1         936 require IO::Async::Socket;
771 1         4 $handle_class = "IO::Async::Socket";
772             }
773             else {
774 233         13404 require IO::Async::Stream;
775 233         854 $handle_class = "IO::Async::Stream";
776             }
777              
778             my $handle = $handle_class->new(
779             notifier_name => $fd eq "0" ? "stdin" :
780             $fd eq "1" ? "stdout" :
781             $fd eq "2" ? "stderr" :
782             $fd eq "io" ? "stdio" : "fd$fd",
783 234 50       1370 %{ $opts->{handle} },
  234 100       1739  
    100          
    100          
784             );
785              
786 234 100       627 if( defined $opts->{from} ) {
787             $handle->write( $opts->{from},
788             on_flush => sub {
789 17     17   259 my ( $handle ) = @_;
790 17         442 $handle->close_write;
791             },
792 23         381 );
793             }
794              
795             $handle
796 234         1662 };
797             }
798              
799             =head2 stdin
800              
801             =head2 stdout
802              
803             =head2 stderr
804              
805             =head2 stdio
806              
807             $stream = $process->stdin
808              
809             $stream = $process->stdout
810              
811             $stream = $process->stderr
812              
813             $stream = $process->stdio
814              
815             Shortcuts for calling C with 0, 1, 2 or C respectively, to obtain the
816             L representing the standard input, output, error, or
817             combined input/output streams of the child process.
818              
819             =cut
820              
821 64     64 1 394 sub stdin { shift->fd( 0 ) }
822 80     80 1 510 sub stdout { shift->fd( 1 ) }
823 26     26 1 311 sub stderr { shift->fd( 2 ) }
824 33     33 1 182 sub stdio { shift->fd( 'io' ) }
825              
826             =head1 EXAMPLES
827              
828             =head2 Capturing the STDOUT stream of a process
829              
830             By configuring the C filehandle of the process using the C key,
831             data written by the process can be captured.
832              
833             my $stdout;
834             my $process = IO::Async::Process->new(
835             command => [ "writing-program", "arguments" ],
836             stdout => { into => \$stdout },
837             on_finish => sub {
838             my $process = shift;
839             my ( $exitcode ) = @_;
840             print "Process has exited with code $exitcode, and wrote:\n";
841             print $stdout;
842             }
843             );
844              
845             $loop->add( $process );
846              
847             Note that until C is invoked, no guarantees are made about how much
848             of the data actually written by the process is yet in the C<$stdout> scalar.
849              
850             See also the C method of L.
851              
852             To handle data more interactively as it arrives, the C key can
853             instead be used, to provide a callback function to invoke whenever more data
854             is available from the process.
855              
856             my $process = IO::Async::Process->new(
857             command => [ "writing-program", "arguments" ],
858             stdout => {
859             on_read => sub {
860             my ( $stream, $buffref ) = @_;
861             while( $$buffref =~ s/^(.*)\n// ) {
862             print "The process wrote a line: $1\n";
863             }
864              
865             return 0;
866             },
867             },
868             on_finish => sub {
869             print "The process has finished\n";
870             }
871             );
872              
873             $loop->add( $process );
874              
875             If the code to handle data read from the process isn't available yet when
876             the object is constructed, it can be supplied later by using the C
877             method on the C filestream at some point before it gets added to the
878             Loop. In this case, C should be configured using C in the
879             C key.
880              
881             my $process = IO::Async::Process->new(
882             command => [ "writing-program", "arguments" ],
883             stdout => { via => "pipe_read" },
884             on_finish => sub {
885             print "The process has finished\n";
886             }
887             );
888              
889             $process->stdout->configure(
890             on_read => sub {
891             my ( $stream, $buffref ) = @_;
892             while( $$buffref =~ s/^(.*)\n// ) {
893             print "The process wrote a line: $1\n";
894             }
895              
896             return 0;
897             },
898             );
899              
900             $loop->add( $process );
901              
902             =head2 Sending data to STDIN of a process
903              
904             By configuring the C filehandle of the process using the C key,
905             data can be written into the C stream of the process.
906              
907             my $process = IO::Async::Process->new(
908             command => [ "reading-program", "arguments" ],
909             stdin => { from => "Here is the data to send\n" },
910             on_finish => sub {
911             print "The process has finished\n";
912             }
913             );
914              
915             $loop->add( $process );
916              
917             The data in this scalar will be written until it is all consumed, then the
918             handle will be closed. This may be useful if the program waits for EOF on
919             C before it exits.
920              
921             To have the ability to write more data into the process once it has started.
922             the C method on the C stream can be used, when it is configured
923             using the C value for C:
924              
925             my $process = IO::Async::Process->new(
926             command => [ "reading-program", "arguments" ],
927             stdin => { via => "pipe_write" },
928             on_finish => sub {
929             print "The process has finished\n";
930             }
931             );
932              
933             $loop->add( $process );
934              
935             $process->stdin->write( "Here is some more data\n" );
936              
937             =head2 Setting socket options
938              
939             By using the C code block you can change the socket receive buffer
940             size at both ends of the socket before the child is forked (at which point it
941             would be too late for the parent to be able to change the child end of the
942             socket).
943              
944             use Socket qw( SOL_SOCKET SO_RCVBUF );
945              
946             my $process = IO::Async::Process->new(
947             command => [ "command-to-read-from-and-write-to", "arguments" ],
948             stdio => {
949             via => "socketpair",
950             prefork => sub {
951             my ( $parentfd, $childfd ) = @_;
952              
953             # Set parent end of socket receive buffer to 3 MB
954             $parentfd->setsockopt(SOL_SOCKET, SO_RCVBUF, 3 * 1024 * 1024);
955             # Set child end of socket receive buffer to 3 MB
956             $childfd ->setsockopt(SOL_SOCKET, SO_RCVBUF, 3 * 1024 * 1024);
957             },
958             },
959             );
960              
961             $loop->add( $process );
962              
963             =cut
964              
965             =head1 AUTHOR
966              
967             Paul Evans
968              
969             =cut
970              
971             0x55AA;