1IO::Async::Process(3) User Contributed Perl DocumentationIO::Async::Process(3)
2
3
4

NAME

6       "IO::Async::Process" - start and manage a child process
7

SYNOPSIS

9        use IO::Async::Process;
10
11        use IO::Async::Loop;
12        my $loop = IO::Async::Loop->new;
13
14        my $process = IO::Async::Process->new(
15           command => [ "tr", "a-z", "n-za-m" ],
16           stdin => {
17              from => "hello world\n",
18           },
19           stdout => {
20              on_read => sub {
21                 my ( $stream, $buffref ) = @_;
22                 while( $$buffref =~ s/^(.*)\n// ) {
23                    print "Rot13 of 'hello world' is '$1'\n";
24                 }
25
26                 return 0;
27              },
28           },
29
30           on_finish => sub {
31              $loop->stop;
32           },
33        );
34
35        $loop->add( $process );
36
37        $loop->run;
38
39       Also accessible via the "open_process" in IO::Async::Loop method:
40
41        $loop->open_process(
42           command => [ "/bin/ping", "-c4", "some.host" ],
43
44           stdout => {
45              on_read => sub {
46                 my ( $stream, $buffref, $eof ) = @_;
47                 while( $$buffref =~ s/^(.*)\n// ) {
48                    print "PING wrote: $1\n";
49                 }
50                 return 0;
51              },
52           },
53
54           on_finish => sub {
55              my $process = shift;
56              my ( $exitcode ) = @_;
57              my $status = ( $exitcode >> 8 );
58              ...
59           },
60        );
61

DESCRIPTION

63       This subclass of IO::Async::Notifier starts a child process, and
64       invokes a callback when it exits. The child process can either execute
65       a given block of code (via fork(2)), or a command.
66

EVENTS

68       The following events are invoked, either using subclass methods or CODE
69       references in parameters:
70
71   on_finish $exitcode
72       Invoked after the process has exited by normal means (i.e. an exit(2)
73       syscall from a process, or "return"ing from the code block), and has
74       closed all its file descriptors.
75
76   on_exception $exception, $errno, $exitcode
77       Invoked when the process exits by an exception from "code", or by
78       failing to exec(2) the given command. $errno will be a dualvar,
79       containing both number and string values. After a successful "exec()"
80       call, this condition can no longer happen.
81
82       Note that this has a different name and a different argument order from
83       "Loop->open_process"'s "on_error".
84
85       If this is not provided and the process exits with an exception, then
86       "on_finish" is invoked instead, being passed just the exit code.
87
88       Since this is just the results of the underlying "$loop->spawn_child"
89       "on_exit" handler in a different order it is possible that the
90       $exception field will be an empty string. It will however always be
91       defined. This can be used to distinguish the two cases:
92
93        on_exception => sub {
94           my $self = shift;
95           my ( $exception, $errno, $exitcode ) = @_;
96
97           if( length $exception ) {
98              print STDERR "The process died with the exception $exception " .
99                 "(errno was $errno)\n";
100           }
101           elsif( ( my $status = W_EXITSTATUS($exitcode) ) == 255 ) {
102              print STDERR "The process failed to exec() - $errno\n";
103           }
104           else {
105              print STDERR "The process exited with exit status $status\n";
106           }
107        }
108

CONSTRUCTOR

110   new
111          $process = IO::Async::Process->new( %args )
112
113       Constructs a new "IO::Async::Process" object and returns it.
114
115       Once constructed, the "Process" will need to be added to the "Loop"
116       before the child process is started.
117

PARAMETERS

119       The following named parameters may be passed to "new" or "configure":
120
121   on_finish => CODE
122   on_exception => CODE
123       CODE reference for the event handlers.
124
125       Once the "on_finish" continuation has been invoked, the
126       "IO::Async::Process" object is removed from the containing
127       IO::Async::Loop object.
128
129       The following parameters may be passed to "new", or to "configure"
130       before the process has been started (i.e. before it has been added to
131       the "Loop").  Once the process is running these cannot be changed.
132
133   command => ARRAY or STRING
134       Either a reference to an array containing the command and its
135       arguments, or a plain string containing the command. This value is
136       passed into perl's exec(2) function.
137
138   code => CODE
139       A block of code to execute in the child process. It will be called in
140       scalar context inside an "eval" block.
141
142   setup => ARRAY
143       Optional reference to an array to pass to the underlying "Loop"
144       "spawn_child" method.
145
146   fdn => HASH
147       A hash describing how to set up file descriptor n. The hash may contain
148       the following keys:
149
150       via => STRING
151           Configures how this file descriptor will be configured for the
152           child process.  Must be given one of the following mode names:
153
154           pipe_read
155               The child will be given the writing end of a pipe(2); the
156               parent may read from the other.
157
158           pipe_write
159               The child will be given the reading end of a pipe(2); the
160               parent may write to the other. Since an EOF condition of this
161               kind of handle cannot reliably be detected, "on_finish" will
162               not wait for this type of pipe to be closed.
163
164           pipe_rdwr
165               Only valid on the "stdio" filehandle. The child will be given
166               the reading end of one pipe(2) on STDIN and the writing end of
167               another on STDOUT. A single Stream object will be created in
168               the parent configured for both filehandles.
169
170           socketpair
171               The child will be given one end of a socketpair(2); the parent
172               will be given the other. The family of this socket may be given
173               by the extra key called "family"; defaulting to "unix". The
174               socktype of this socket may be given by the extra key called
175               "socktype"; defaulting to "stream". If the type is not
176               "SOCK_STREAM" then a IO::Async::Socket object will be
177               constructed for the parent side of the handle, rather than
178               IO::Async::Stream.
179
180           Once the filehandle is set up, the "fd" method (or its shortcuts of
181           "stdin", "stdout" or "stderr") may be used to access the
182           IO::Async::Handle-subclassed object wrapped around it.
183
184           The value of this argument is implied by any of the following
185           alternatives.
186
187       on_read => CODE
188           The child will be given the writing end of a pipe. The reading end
189           will be wrapped by an IO::Async::Stream using this "on_read"
190           callback function.
191
192       into => SCALAR
193           The child will be given the writing end of a pipe. The referenced
194           scalar will be filled by data read from the child process. This
195           data may not be available until the pipe has been closed by the
196           child.
197
198       from => STRING
199           The child will be given the reading end of a pipe. The string given
200           by the "from" parameter will be written to the child. When all of
201           the data has been written the pipe will be closed.
202
203       prefork => CODE
204           Only valid for handles with a "via" of "socketpair". The code block
205           runs after the socketpair(2) is created, but before the child is
206           forked. This is handy for when you adjust both ends of the created
207           socket (for example, to use setsockopt(3)) from the controlling
208           parent, before the child code runs.  The arguments passed in are
209           the IO::Socket objects for the parent and child ends of the socket.
210
211            $prefork->( $localfd, $childfd )
212
213   stdin => ...
214   stdout => ...
215   stderr => ...
216       Shortcuts for "fd0", "fd1" and "fd2" respectively.
217
218   stdio => ...
219       Special filehandle to affect STDIN and STDOUT at the same time. This
220       filehandle supports being configured for both reading and writing at
221       the same time.
222

METHODS

224   pid
225          $pid = $process->pid
226
227       Returns the process ID of the process, if it has been started, or
228       "undef" if not. Its value is preserved after the process exits, so it
229       may be inspected during the "on_finish" or "on_exception" events.
230
231   kill
232          $process->kill( $signal )
233
234       Sends a signal to the process
235
236   is_running
237          $running = $process->is_running
238
239       Returns true if the Process has been started, and has not yet finished.
240
241   is_exited
242          $exited = $process->is_exited
243
244       Returns true if the Process has finished running, and finished due to
245       normal exit(2).
246
247   exitstatus
248          $status = $process->exitstatus
249
250       If the process exited due to normal exit(2), returns the value that was
251       passed to exit(2). Otherwise, returns "undef".
252
253   exception
254          $exception = $process->exception
255
256       If the process exited due to an exception, returns the exception that
257       was thrown. Otherwise, returns "undef".
258
259   errno
260          $errno = $process->errno
261
262       If the process exited due to an exception, returns the numerical value
263       of $! at the time the exception was thrown. Otherwise, returns "undef".
264
265   errstr
266          $errstr = $process->errstr
267
268       If the process exited due to an exception, returns the string value of
269       $! at the time the exception was thrown. Otherwise, returns "undef".
270
271   fd
272          $stream = $process->fd( $fd )
273
274       Returns the IO::Async::Stream or IO::Async::Socket associated with the
275       given FD number. This must have been set up by a "configure" argument
276       prior to adding the "Process" object to the "Loop".
277
278       The returned object have its read or write handle set to the other end
279       of a pipe or socket connected to that FD number in the child process.
280       Typically, this will be used to call the "write" method on, to write
281       more data into the child, or to set an "on_read" handler to read data
282       out of the child.
283
284       The "on_closed" event for these streams must not be changed, or it will
285       break the close detection used by the "Process" object and the
286       "on_finish" event will not be invoked.
287
288   stdin
289   stdout
290   stderr
291   stdio
292          $stream = $process->stdin
293
294          $stream = $process->stdout
295
296          $stream = $process->stderr
297
298          $stream = $process->stdio
299
300       Shortcuts for calling "fd" with 0, 1, 2 or "io" respectively, to obtain
301       the IO::Async::Stream representing the standard input, output, error,
302       or combined input/output streams of the child process.
303

EXAMPLES

305   Capturing the STDOUT stream of a process
306       By configuring the "stdout" filehandle of the process using the "into"
307       key, data written by the process can be captured.
308
309        my $stdout;
310        my $process = IO::Async::Process->new(
311           command => [ "writing-program", "arguments" ],
312           stdout => { into => \$stdout },
313           on_finish => sub {
314              my $process = shift;
315              my ( $exitcode ) = @_;
316              print "Process has exited with code $exitcode, and wrote:\n";
317              print $stdout;
318           }
319        );
320
321        $loop->add( $process );
322
323       Note that until "on_finish" is invoked, no guarantees are made about
324       how much of the data actually written by the process is yet in the
325       $stdout scalar.
326
327       See also the "run_child" method of IO::Async::Loop.
328
329       To handle data more interactively as it arrives, the "on_read" key can
330       instead be used, to provide a callback function to invoke whenever more
331       data is available from the process.
332
333        my $process = IO::Async::Process->new(
334           command => [ "writing-program", "arguments" ],
335           stdout => {
336              on_read => sub {
337                 my ( $stream, $buffref ) = @_;
338                 while( $$buffref =~ s/^(.*)\n// ) {
339                    print "The process wrote a line: $1\n";
340                 }
341
342                 return 0;
343              },
344           },
345           on_finish => sub {
346              print "The process has finished\n";
347           }
348        );
349
350        $loop->add( $process );
351
352       If the code to handle data read from the process isn't available yet
353       when the object is constructed, it can be supplied later by using the
354       "configure" method on the "stdout" filestream at some point before it
355       gets added to the Loop. In this case, "stdin" should be configured
356       using "pipe_read" in the "via" key.
357
358        my $process = IO::Async::Process->new(
359           command => [ "writing-program", "arguments" ],
360           stdout => { via => "pipe_read" },
361           on_finish => sub {
362              print "The process has finished\n";
363           }
364        );
365
366        $process->stdout->configure(
367           on_read => sub {
368              my ( $stream, $buffref ) = @_;
369              while( $$buffref =~ s/^(.*)\n// ) {
370                 print "The process wrote a line: $1\n";
371              }
372
373              return 0;
374           },
375        );
376
377        $loop->add( $process );
378
379   Sending data to STDIN of a process
380       By configuring the "stdin" filehandle of the process using the "from"
381       key, data can be written into the "STDIN" stream of the process.
382
383        my $process = IO::Async::Process->new(
384           command => [ "reading-program", "arguments" ],
385           stdin => { from => "Here is the data to send\n" },
386           on_finish => sub {
387              print "The process has finished\n";
388           }
389        );
390
391        $loop->add( $process );
392
393       The data in this scalar will be written until it is all consumed, then
394       the handle will be closed. This may be useful if the program waits for
395       EOF on "STDIN" before it exits.
396
397       To have the ability to write more data into the process once it has
398       started.  the "write" method on the "stdin" stream can be used, when it
399       is configured using the "pipe_write" value for "via":
400
401        my $process = IO::Async::Process->new(
402           command => [ "reading-program", "arguments" ],
403           stdin => { via => "pipe_write" },
404           on_finish => sub {
405              print "The process has finished\n";
406           }
407        );
408
409        $loop->add( $process );
410
411        $process->stdin->write( "Here is some more data\n" );
412
413   Setting socket options
414       By using the "prefork" code block you can change the socket receive
415       buffer size at both ends of the socket before the child is forked (at
416       which point it would be too late for the parent to be able to change
417       the child end of the socket).
418
419        use Socket qw( SOL_SOCKET SO_RCVBUF );
420
421        my $process = IO::Async::Process->new(
422           command => [ "command-to-read-from-and-write-to", "arguments" ],
423           stdio => {
424              via => "socketpair",
425              prefork => sub {
426                 my ( $parentfd, $childfd ) = @_;
427
428                 # Set parent end of socket receive buffer to 3 MB
429                 $parentfd->setsockopt(SOL_SOCKET, SO_RCVBUF, 3 * 1024 * 1024);
430                 # Set child end of socket receive buffer to 3 MB
431                 $childfd ->setsockopt(SOL_SOCKET, SO_RCVBUF, 3 * 1024 * 1024);
432              },
433           },
434        );
435
436        $loop->add( $process );
437

AUTHOR

439       Paul Evans <leonerd@leonerd.org.uk>
440
441
442
443perl v5.30.0                      2019-07-26             IO::Async::Process(3)
Impressum