1IPC::Cmd(3) User Contributed Perl Documentation IPC::Cmd(3)
2
3
4
6 IPC::Cmd - finding and running system commands made easy
7
9 use IPC::Cmd qw[can_run run run_forked];
10
11 my $full_path = can_run('wget') or warn 'wget is not installed!';
12
13 ### commands can be arrayrefs or strings ###
14 my $cmd = "$full_path -b theregister.co.uk";
15 my $cmd = [$full_path, '-b', 'theregister.co.uk'];
16
17 ### in scalar context ###
18 my $buffer;
19 if( scalar run( command => $cmd,
20 verbose => 0,
21 buffer => \$buffer,
22 timeout => 20 )
23 ) {
24 print "fetched webpage successfully: $buffer\n";
25 }
26
27
28 ### in list context ###
29 my( $success, $error_message, $full_buf, $stdout_buf, $stderr_buf ) =
30 run( command => $cmd, verbose => 0 );
31
32 if( $success ) {
33 print "this is what the command printed:\n";
34 print join "", @$full_buf;
35 }
36
37 ### run_forked example ###
38 my $result = run_forked("$full_path -q -O - theregister.co.uk", {'timeout' => 20});
39 if ($result->{'exit_code'} eq 0 && !$result->{'timeout'}) {
40 print "this is what wget returned:\n";
41 print $result->{'stdout'};
42 }
43
44 ### check for features
45 print "IPC::Open3 available: " . IPC::Cmd->can_use_ipc_open3;
46 print "IPC::Run available: " . IPC::Cmd->can_use_ipc_run;
47 print "Can capture buffer: " . IPC::Cmd->can_capture_buffer;
48
49 ### don't have IPC::Cmd be verbose, ie don't print to stdout or
50 ### stderr when running commands -- default is '0'
51 $IPC::Cmd::VERBOSE = 0;
52
54 IPC::Cmd allows you to run commands platform independently,
55 interactively if desired, but have them still work.
56
57 The "can_run" function can tell you if a certain binary is installed
58 and if so where, whereas the "run" function can actually execute any of
59 the commands you give it and give you a clear return value, as well as
60 adhere to your verbosity settings.
61
63 $ipc_run_version = IPC::Cmd->can_use_ipc_run( [VERBOSE] )
64 Utility function that tells you if "IPC::Run" is available. If the
65 "verbose" flag is passed, it will print diagnostic messages if IPC::Run
66 can not be found or loaded.
67
68 $ipc_open3_version = IPC::Cmd->can_use_ipc_open3( [VERBOSE] )
69 Utility function that tells you if "IPC::Open3" is available. If the
70 verbose flag is passed, it will print diagnostic messages if
71 "IPC::Open3" can not be found or loaded.
72
73 $bool = IPC::Cmd->can_capture_buffer
74 Utility function that tells you if "IPC::Cmd" is capable of capturing
75 buffers in it's current configuration.
76
77 $bool = IPC::Cmd->can_use_run_forked
78 Utility function that tells you if "IPC::Cmd" is capable of providing
79 "run_forked" on the current platform.
80
82 $path = can_run( PROGRAM );
83 "can_run" takes only one argument: the name of a binary you wish to
84 locate. "can_run" works much like the unix binary "which" or the bash
85 command "type", which scans through your path, looking for the
86 requested binary.
87
88 Unlike "which" and "type", this function is platform independent and
89 will also work on, for example, Win32.
90
91 If called in a scalar context it will return the full path to the
92 binary you asked for if it was found, or "undef" if it was not.
93
94 If called in a list context and the global variable $INSTANCES is a
95 true value, it will return a list of the full paths to instances of the
96 binary where found in "PATH", or an empty list if it was not found.
97
98 $ok | ($ok, $err, $full_buf, $stdout_buff, $stderr_buff) = run( command =>
99 COMMAND, [verbose => BOOL, buffer => \$SCALAR, timeout => DIGIT] );
100 "run" takes 4 arguments:
101
102 command
103 This is the command to execute. It may be either a string or an
104 array reference. This is a required argument.
105
106 See "Caveats" for remarks on how commands are parsed and their
107 limitations.
108
109 verbose
110 This controls whether all output of a command should also be
111 printed to STDOUT/STDERR or should only be trapped in buffers
112 (NOTE: buffers require IPC::Run to be installed, or your system
113 able to work with IPC::Open3).
114
115 It will default to the global setting of $IPC::Cmd::VERBOSE, which
116 by default is 0.
117
118 buffer
119 This will hold all the output of a command. It needs to be a
120 reference to a scalar. Note that this will hold both the STDOUT
121 and STDERR messages, and you have no way of telling which is which.
122 If you require this distinction, run the "run" command in list
123 context and inspect the individual buffers.
124
125 Of course, this requires that the underlying call supports buffers.
126 See the note on buffers above.
127
128 timeout
129 Sets the maximum time the command is allowed to run before
130 aborting, using the built-in "alarm()" call. If the timeout is
131 triggered, the "errorcode" in the return value will be set to an
132 object of the "IPC::Cmd::TimeOut" class. See the "error message"
133 section below for details.
134
135 Defaults to 0, meaning no timeout is set.
136
137 "run" will return a simple "true" or "false" when called in scalar
138 context. In list context, you will be returned a list of the following
139 items:
140
141 success
142 A simple boolean indicating if the command executed without errors
143 or not.
144
145 error message
146 If the first element of the return value ("success") was 0, then
147 some error occurred. This second element is the error message the
148 command you requested exited with, if available. This is generally
149 a pretty printed value of $? or $@. See "perldoc perlvar" for
150 details on what they can contain. If the error was a timeout, the
151 "error message" will be prefixed with the string
152 "IPC::Cmd::TimeOut", the timeout class.
153
154 full_buffer
155 This is an array reference containing all the output the command
156 generated. Note that buffers are only available if you have
157 IPC::Run installed, or if your system is able to work with
158 IPC::Open3 -- see below). Otherwise, this element will be "undef".
159
160 out_buffer
161 This is an array reference containing all the output sent to STDOUT
162 the command generated. The notes from "full_buffer" apply.
163
164 error_buffer
165 This is an arrayreference containing all the output sent to STDERR
166 the command generated. The notes from "full_buffer" apply.
167
168 See the "HOW IT WORKS" section below to see how "IPC::Cmd" decides what
169 modules or function calls to use when issuing a command.
170
171 $hashref = run_forked( COMMAND, { child_stdin => SCALAR, timeout => DIGIT,
172 stdout_handler => CODEREF, stderr_handler => CODEREF} );
173 "run_forked" is used to execute some program or a coderef, optionally
174 feed it with some input, get its return code and output (both stdout
175 and stderr into separate buffers). In addition, it allows to terminate
176 the program if it takes too long to finish.
177
178 The important and distinguishing feature of run_forked is execution
179 timeout which at first seems to be quite a simple task but if you think
180 that the program which you're spawning might spawn some children itself
181 (which in their turn could do the same and so on) it turns out to be
182 not a simple issue.
183
184 "run_forked" is designed to survive and successfully terminate almost
185 any long running task, even a fork bomb in case your system has the
186 resources to survive during given timeout.
187
188 This is achieved by creating separate watchdog process which spawns the
189 specified program in a separate process session and supervises it:
190 optionally feeds it with input, stores its exit code, stdout and
191 stderr, terminates it in case it runs longer than specified.
192
193 Invocation requires the command to be executed or a coderef and
194 optionally a hashref of options:
195
196 "timeout"
197 Specify in seconds how long to run the command before it is killed
198 with SIG_KILL (9), which effectively terminates it and all of its
199 children (direct or indirect).
200
201 "child_stdin"
202 Specify some text that will be passed into the "STDIN" of the
203 executed program.
204
205 "stdout_handler"
206 Coderef of a subroutine to call when a portion of data is received
207 on STDOUT from the executing program.
208
209 "stderr_handler"
210 Coderef of a subroutine to call when a portion of data is received
211 on STDERR from the executing program.
212
213 "wait_loop_callback"
214 Coderef of a subroutine to call inside of the main waiting loop
215 (while "run_forked" waits for the external to finish or fail). It
216 is useful to stop running external process before it ends by
217 itself, e.g.
218
219 my $r = run_forked("some external command", {
220 'wait_loop_callback' => sub {
221 if (condition) {
222 kill(1, $$);
223 }
224 },
225 'terminate_on_signal' => 'HUP',
226 });
227
228 Combined with "stdout_handler" and "stderr_handler" allows
229 terminating external command based on its output. Could also be
230 used as a timer without engaging with alarm (signals).
231
232 Remember that this code could be called every millisecond
233 (depending on the output which external command generates), so try
234 to make it as lightweight as possible.
235
236 "discard_output"
237 Discards the buffering of the standard output and standard errors
238 for return by run_forked(). With this option you have to use the
239 std*_handlers to read what the command outputs. Useful for
240 commands that send a lot of output.
241
242 "terminate_on_parent_sudden_death"
243 Enable this option if you wish all spawned processes to be killed
244 if the initially spawned process (the parent) is killed or dies
245 without waiting for child processes.
246
247 "run_forked" will return a HASHREF with the following keys:
248
249 "exit_code"
250 The exit code of the executed program.
251
252 "timeout"
253 The number of seconds the program ran for before being terminated,
254 or 0 if no timeout occurred.
255
256 "stdout"
257 Holds the standard output of the executed command (or empty string
258 if there was no STDOUT output or if "discard_output" was used; it's
259 always defined!)
260
261 "stderr"
262 Holds the standard error of the executed command (or empty string
263 if there was no STDERR output or if "discard_output" was used; it's
264 always defined!)
265
266 "merged"
267 Holds the standard output and error of the executed command merged
268 into one stream (or empty string if there was no output at all or
269 if "discard_output" was used; it's always defined!)
270
271 "err_msg"
272 Holds some explanation in the case of an error.
273
274 $q = QUOTE
275 Returns the character used for quoting strings on this platform. This
276 is usually a "'" (single quote) on most systems, but some systems use
277 different quotes. For example, "Win32" uses """ (double quote).
278
279 You can use it as follows:
280
281 use IPC::Cmd qw[run QUOTE];
282 my $cmd = q[echo ] . QUOTE . q[foo bar] . QUOTE;
283
284 This makes sure that "foo bar" is treated as a string, rather than two
285 separate arguments to the "echo" function.
286
288 "run" will try to execute your command using the following logic:
289
290 • If you have "IPC::Run" installed, and the variable
291 $IPC::Cmd::USE_IPC_RUN is set to true (See the "Global Variables"
292 section) use that to execute the command. You will have the full
293 output available in buffers, interactive commands are sure to work
294 and you are guaranteed to have your verbosity settings honored
295 cleanly.
296
297 • Otherwise, if the variable $IPC::Cmd::USE_IPC_OPEN3 is set to true
298 (See the "Global Variables" section), try to execute the command
299 using IPC::Open3. Buffers will be available on all platforms,
300 interactive commands will still execute cleanly, and also your
301 verbosity settings will be adhered to nicely;
302
303 • Otherwise, if you have the "verbose" argument set to true, we fall
304 back to a simple "system()" call. We cannot capture any buffers,
305 but interactive commands will still work.
306
307 • Otherwise we will try and temporarily redirect STDERR and STDOUT,
308 do a "system()" call with your command and then re-open STDERR and
309 STDOUT. This is the method of last resort and will still allow you
310 to execute your commands cleanly. However, no buffers will be
311 available.
312
314 The behaviour of IPC::Cmd can be altered by changing the following
315 global variables:
316
317 $IPC::Cmd::VERBOSE
318 This controls whether IPC::Cmd will print any output from the commands
319 to the screen or not. The default is 0.
320
321 $IPC::Cmd::USE_IPC_RUN
322 This variable controls whether IPC::Cmd will try to use IPC::Run when
323 available and suitable.
324
325 $IPC::Cmd::USE_IPC_OPEN3
326 This variable controls whether IPC::Cmd will try to use IPC::Open3 when
327 available and suitable. Defaults to true.
328
329 $IPC::Cmd::WARN
330 This variable controls whether run-time warnings should be issued, like
331 the failure to load an "IPC::*" module you explicitly requested.
332
333 Defaults to true. Turn this off at your own risk.
334
335 $IPC::Cmd::INSTANCES
336 This variable controls whether "can_run" will return all instances of
337 the binary it finds in the "PATH" when called in a list context.
338
339 Defaults to false, set to true to enable the described behaviour.
340
341 $IPC::Cmd::ALLOW_NULL_ARGS
342 This variable controls whether "run" will remove any empty/null
343 arguments it finds in command arguments.
344
345 Defaults to false, so it will remove null arguments. Set to true to
346 allow them.
347
349 Whitespace and IPC::Open3 / system()
350 When using "IPC::Open3" or "system", if you provide a string as the
351 "command" argument, it is assumed to be appropriately escaped. You
352 can use the "QUOTE" constant to use as a portable quote character
353 (see above). However, if you provide an array reference, special
354 rules apply:
355
356 If your command contains special characters (< > | &), it will be
357 internally stringified before executing the command, to avoid that
358 these special characters are escaped and passed as arguments
359 instead of retaining their special meaning.
360
361 However, if the command contained arguments that contained
362 whitespace, stringifying the command would lose the significance of
363 the whitespace. Therefore, "IPC::Cmd" will quote any arguments
364 containing whitespace in your command if the command is passed as
365 an arrayref and contains special characters.
366
367 Whitespace and IPC::Run
368 When using "IPC::Run", if you provide a string as the "command"
369 argument, the string will be split on whitespace to determine the
370 individual elements of your command. Although this will usually
371 just Do What You Mean, it may break if you have files or commands
372 with whitespace in them.
373
374 If you do not wish this to happen, you should provide an array
375 reference, where all parts of your command are already separated
376 out. Note however, if there are extra or spurious whitespaces in
377 these parts, the parser or underlying code may not interpret it
378 correctly, and cause an error.
379
380 Example: The following code
381
382 gzip -cdf foo.tar.gz | tar -xf -
383
384 should either be passed as
385
386 "gzip -cdf foo.tar.gz | tar -xf -"
387
388 or as
389
390 ['gzip', '-cdf', 'foo.tar.gz', '|', 'tar', '-xf', '-']
391
392 But take care not to pass it as, for example
393
394 ['gzip -cdf foo.tar.gz', '|', 'tar -xf -']
395
396 Since this will lead to issues as described above.
397
398 IO Redirect
399 Currently it is too complicated to parse your command for IO
400 redirections. For capturing STDOUT or STDERR there is a work around
401 however, since you can just inspect your buffers for the contents.
402
403 Interleaving STDOUT/STDERR
404 Neither IPC::Run nor IPC::Open3 can interleave STDOUT and STDERR.
405 For short bursts of output from a program, e.g. this sample,
406
407 for ( 1..4 ) {
408 $_ % 2 ? print STDOUT $_ : print STDERR $_;
409 }
410
411 IPC::[Run|Open3] will first read all of STDOUT, then all of STDERR,
412 meaning the output looks like '13' on STDOUT and '24' on STDERR,
413 instead of
414
415 1
416 2
417 3
418 4
419
420 This has been recorded in rt.cpan.org as bug #37532: Unable to
421 interleave STDOUT and STDERR.
422
424 IPC::Run, IPC::Open3
425
427 Thanks to James Mastros and Martijn van der Streek for their help in
428 getting IPC::Open3 to behave nicely.
429
430 Thanks to Petya Kohts for the "run_forked" code.
431
433 Please report bugs or other issues to <bug-ipc-cmd@rt.cpan.org>.
434
436 Original author: Jos Boumans <kane@cpan.org>. Current maintainer:
437 Chris Williams <bingos@cpan.org>.
438
440 This library is free software; you may redistribute and/or modify it
441 under the same terms as Perl itself.
442
443
444
445perl v5.34.0 2022-01-21 IPC::Cmd(3)