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 ( $pid, $exitcode ) = @_;
56              my $status = ( $exitcode >> 8 );
57              ...
58           },
59        );
60

DESCRIPTION

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

EVENTS

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

CONSTRUCTOR

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

PARAMETERS

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

METHODS

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

EXAMPLES

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

AUTHOR

435       Paul Evans <leonerd@leonerd.org.uk>
436
437
438
439perl v5.28.0                      2018-07-14             IO::Async::Process(3)
Impressum