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