IPC::Cmd(3pm)
π IPC::Cmd(3pm)
okay so bestie, welcome to IPC::Cmd from the Perl Programmers Reference Guide β this is the page that makes running system commands, like, actually easy instead of a whole ordeal. sit down, grab a strawberry drink π, we're doing this.
β¨ SYNOPSIS β¨
use IPC::Cmd qw[can_run run run_forked];
my $full_path = can_run('wget') or warn 'wget is not installed!';
### commands can be arrayrefs or strings ###
my $cmd = "$full_path -b theregister.co.uk";
my $cmd = [$full_path, '-b', 'theregister.co.uk'];
### in scalar context ###
my $buffer;
if( scalar run( command => $cmd,
verbose => 0,
buffer => \$buffer,
timeout => 20 )
) {
print "fetched webpage successfully: $buffer\n";
}
### in list context ###
my( $success, $error_message, $full_buf, $stdout_buf, $stderr_buf ) =
run( command => $cmd, verbose => 0 );
if( $success ) {
print "this is what the command printed:\n";
print join "", @$full_buf;
}
### run_forked example ###
my $result = run_forked("$full_path -q -O - theregister.co.uk", {'timeout' => 20});
if ($result->{'exit_code'} eq 0 && !$result->{'timeout'}) {
print "this is what wget returned:\n";
print $result->{'stdout'};
}
### check for features
print "IPC::Open3 available: " . IPC::Cmd->can_use_ipc_open3;
print "IPC::Run available: " . IPC::Cmd->can_use_ipc_run;
print "Can capture buffer: " . IPC::Cmd->can_capture_buffer;
### don't have IPC::Cmd be verbose, ie don't print to stdout or
### stderr when running commands -- default is '0'
$IPC::Cmd::VERBOSE = 0;
like, look at that. no cap, it's genuinely that clean π«Ά
πΈ DESCRIPTION πΈ
IPC::Cmd lets you run commands platform independently β interactively if that's the vibe you want β and they still work. iconic behavior honestly π
The can_run function tells you whether a certain binary is installed and, if it is, where it lives. meanwhile run is the main character: it actually executes any of the commands you hand it, gives you back a clear return value, and respects your verbosity settings. periodt. π
π¦ CLASS METHODS π¦
$ipc_run_version = IPC::Cmd->can_use_ipc_run( [VERBOSE] )
utility function that tells you if IPC::Run is available β¨ if you pass the verbose flag, it'll print diagnostic messages when IPC::Run can't be found or can't be loaded. thoughtful of it tbh.
$ipc_open3_version = IPC::Cmd->can_use_ipc_open3( [VERBOSE] )
utility function that tells you if IPC::Open3 is available π if you pass the verbose flag, it'll print diagnostic messages when IPC::Open3 can't be found or can't be loaded.
$bool = IPC::Cmd->can_capture_buffer
utility function that tells you if IPC::Cmd is capable of capturing buffers in its current configuration π
$bool = IPC::Cmd->can_use_run_forked
utility function that tells you if IPC::Cmd is capable of providing run_forked on the current platform π§
π FUNCTIONS π
β¨ $path = can_run( PROGRAM ); β¨
Okay so can_run takes literally only one argument: the name of the binary you want to find. It works a lot like the unix binary which or the bash command type β it scans through your path looking for the binary you asked for. π
But here's the glow-up: unlike which and type, this function is platform independent and will also work on, for example, Win32. π
If called in a scalar context it will return the full path to the binary you asked for if it was found, or undef if it was not. π
If called in a list context and the global variable $INSTANCES is a true value, it will return a list of the full paths to instances of the binary where found in PATH, or an empty list if it was not found. π
π $ok | ($ok, $err, $full_buf, $stdout_buff, $stderr_buff) = run( command => COMMAND, [verbose => BOOL, buffer => \$SCALAR, timeout => DIGIT] ); π
run takes 4 arguments β let's go through them one by one bestie:
commandβ this is the command to execute. It may be either a string or an array reference. This is a required argument. no cap, you must pass it. π«Ά
See "Caveats" for remarks on how commands are parsed and their limitations. π
verboseβ this controls whether all output of a command should also be printed to STDOUT/STDERR or should only be trapped in buffers (NOTE: buffers require IPC::Run to be installed, or your system able to work with IPC::Open3). It will default to the global setting of$IPC::Cmd::VERBOSE, which by default is0. πbufferβ this will hold all the output of a command. It needs to be a reference to a scalar. Note that this will hold both the STDOUT and STDERR messages, and you have no way of telling which is which. π¬ If you require this distinction, run theruncommand in list context and inspect the individual buffers.
Of course, this requires that the underlying call supports buffers. See the note on buffers above. β¬οΈ
timeoutβ sets the maximum time the command is allowed to run before aborting, using the built-inalarm()call. If the timeout is triggered, theerrorcodein the return value will be set to an object of theIPC::Cmd::TimeOutclass. See the "error message" section below for details. Defaults to0, meaning no timeout is set. β°
run will return a simple true or false when called in scalar context. In list context, you will be returned a list of the following items:
successβ a simple boolean indicating if the command executed without errors or not. βerror messageβ if the first element of the return value (success) was0, then some error occurred. This second element is the error message the command you requested exited with, if available. This is generally a pretty printed value of$?or$@. Seeperldoc perlvarfor details on what they can contain. If the error was a timeout, theerror messagewill be prefixed with the stringIPC::Cmd::TimeOut, the timeout class. πfull_bufferβ this is an array reference containing all the output the command generated. Note that buffers are only available if you have IPC::Run installed, or if your system is able to work with IPC::Open3 β see below. Otherwise, this element will beundef. π«₯out_bufferβ this is an array reference containing all the output sent to STDOUT the command generated. The notes fromfull_bufferapply. πΈerror_bufferβ this is an arrayreference containing all the output sent to STDERR the command generated. The notes fromfull_bufferapply. π
See the "HOW IT WORKS" section below to see how IPC::Cmd decides what modules or function calls to use when issuing a command. π§
π¦ $hashref = run_forked( COMMAND, { child_stdin => SCALAR, timeout => DIGIT, stdout_handler => CODEREF, stderr_handler => CODEREF} ); π¦
run_forked is used to execute some program or a coderef, optionally feed it with some input, get its return code and output (both stdout and stderr into separate buffers). In addition, it allows to terminate the program if it takes too long to finish. β³
The important and distinguishing feature of run_forked is execution timeout which at first seems to be quite a simple task but if you think that the program which you're spawning might spawn some children itself (which in their turn could do the same and so on) it turns out to be not a simple issue. π€―
run_forked is designed to survive and successfully terminate almost any long running task, even a fork bomb in case your system has the resources to survive during given timeout. ππ₯
This is achieved by creating separate watchdog process which spawns the specified program in a separate process session and supervises it: optionally feeds it with input, stores its exit code, stdout and stderr, terminates it in case it runs longer than specified. π
Invocation requires the command to be executed or a coderef and optionally a hashref of options:
timeoutβ specify in seconds how long to run the command before it is killed withSIG_KILL(9), which effectively terminates it and all of its children (direct or indirect). β οΈchild_stdinβ specify some text that will be passed into theSTDINof the executed program. πstdout_handlerβ coderef of a subroutine to call when a portion of data is received on STDOUT from the executing program. π€stderr_handlerβ coderef of a subroutine to call when a portion of data is received on STDERR from the executing program. π₯wait_loop_callbackβ coderef of a subroutine to call inside of the main waiting loop (whilerun_forkedwaits for the external to finish or fail). It is useful to stop running external process before it ends by itself, e.g.
my $r = run_forked("some external command", {
'wait_loop_callback' => sub {
if (condition) {
kill(1, $$);
}
},
'terminate_on_signal' => 'HUP',
});
Combined with stdout_handler and stderr_handler allows terminating external command based on its output. Could also be used as a timer without engaging with alarm (signals). β²οΈ
Remember that this code could be called every millisecond (depending on the output which external command generates), so try to make it as lightweight as possible. πββοΈπ¨
discard_outputβ discards the buffering of the standard output and standard errors for return by run_forked(). With this option you have to use the std*_handlers to read what the command outputs. Useful for commands that send a lot of output. ποΈterminate_on_parent_sudden_deathβ enable this option if you wish all spawned processes to be killed if the initially spawned process (the parent) is killed or dies without waiting for child processes. π
run_forked will return a HASHREF with the following keys:
exit_codeβ the exit code of the executed program. π’timeoutβ the number of seconds the program ran for before being terminated, or0if no timeout occurred. β±οΈstdoutβ holds the standard output of the executed command (or empty string if there was no STDOUT output or ifdiscard_outputwas used; it's always defined!). π©·stderrβ holds the standard error of the executed command (or empty string if there was no STDERR output or ifdiscard_outputwas used; it's always defined!). π©΅mergedβ holds the standard output and error of the executed command merged into one stream (or empty string if there was no output at all or ifdiscard_outputwas used; it's always defined!). π«§err_msgβ holds some explanation in the case of an error. π
π $q = QUOTE π
Returns the character used for quoting strings on this platform. This is usually a ' (single quote) on most systems, but some systems use different quotes. For example, Win32 uses " (double quote). π―
You can use it as follows:
use IPC::Cmd qw[run QUOTE];
my $cmd = q[echo ] . QUOTE . q[foo bar] . QUOTE;
This makes sure that foo bar is treated as a string, rather than two separate arguments to the echo function. π
β¨
π₯ HOW IT WORKS π₯
run will try to execute your command using the following logic:
- If you have
IPC::Runinstalled, and the variable$IPC::Cmd::USE_IPC_RUNis set to true (See the "Global Variables" section) use that to execute the command. You will have the full output available in buffers, interactive commands are sure to work and you are guaranteed to have your verbosity settings honored cleanly. π - Otherwise, if the variable
$IPC::Cmd::USE_IPC_OPEN3is set to true (See the "Global Variables" section), try to execute the command using IPC::Open3. Buffers will be available on all platforms, interactive commands will still execute cleanly, and also your verbosity settings will be adhered to nicely; π«Ά - Otherwise, if you have the
verboseargument set to true, we fall back to a simplesystem()call. We cannot capture any buffers, but interactive commands will still work. π§ - Otherwise we will try and temporarily redirect STDERR and STDOUT, do a
system()call with your command and then re-open STDERR and STDOUT. This is the method of last resort and will still allow you to execute your commands cleanly. However, no buffers will be available. π«
π Global Variables π
The behaviour of IPC::Cmd can be altered by changing the following global variables:
β $IPC::Cmd::VERBOSE β
This controls whether IPC::Cmd will print any output from the commands to the screen or not. The default is 0. π
β $IPC::Cmd::USE_IPC_RUN β
This variable controls whether IPC::Cmd will try to use IPC::Run when available and suitable. π
β $IPC::Cmd::USE_IPC_OPEN3 β
This variable controls whether IPC::Cmd will try to use IPC::Open3 when available and suitable. Defaults to true. β
β $IPC::Cmd::WARN β
This variable controls whether run-time warnings should be issued, like the failure to load an IPC::* module you explicitly requested. β οΈ
Defaults to true. Turn this off at your own risk. π
β $IPC::Cmd::INSTANCES β
This variable controls whether can_run will return all instances of the binary it finds in the PATH when called in a list context. ποΈ
Defaults to false, set to true to enable the described behaviour. ποΈ
β $IPC::Cmd::ALLOW_NULL_ARGS β
This variable controls whether run will remove any empty/null arguments it finds in command arguments. π³οΈ
Defaults to false, so it will remove null arguments. Set to true to allow them. π§
πΈ Caveats πΈ
π§Ό Whitespace and IPC::Open3 / system() π§Ό
Okay bestie, listen: when you're using IPC::Open3 or system, and you pass a string as the command argument, it is assumed to be appropriately escaped. You can use the QUOTE constant as a portable quote character (see above). But if you pass an array reference, special rules apply, and they are very much giving βread the fine printβ energy:
- If your command contains special characters (
< > | &), it will be internally stringified before executing the command, so those special characters don't get escaped and passed as arguments instead of keeping their special meaning.
However, if the command contained arguments that contained whitespace, stringifying the command would lose the significance of the whitespace. So therefore, IPC::Cmd will quote any arguments containing whitespace in your command if the command is passed as an arrayref and contains special characters. Slay, but carefully. π
π Whitespace and IPC::Run π
When you're using IPC::Run, if you provide a string as the command argument, the string will be split on whitespace to determine the individual elements of your command. Usually this will just Do What You Mean, but it may break if you have files or commands with whitespace in them. Lowkey a trap, ngl.
If you do not wish this to happen, you should provide an array reference, where all parts of your command are already separated out. Note however: if there are extra or spurious whitespaces in these parts, the parser or underlying code may not interpret it correctly, and cause an error. Not iconic. π
Example: the following code
gzip -cdf foo.tar.gz | tar -xf -
should either be passed as
"gzip -cdf foo.tar.gz | tar -xf -"
or as
['gzip', '-cdf', 'foo.tar.gz', '|', 'tar', '-xf', '-']
But take care not to pass it as, for example
['gzip -cdf foo.tar.gz', '|', 'tar -xf -']
Since this will lead to issues as described above. Do not do it, bestie. π«Ά
π° IO Redirect π°
Currently it is too complicated to parse your command for IO redirections. For capturing STDOUT or STDERR there is a work around however, since you can just inspect your buffers for the contents. So like, not a full glow-up, but it gets the job done. β¨
π Interleaving STDOUT/STDERR π
Neither IPC::Run nor IPC::Open3 can interleave STDOUT and STDERR. For short bursts of output from a program, e.g. this sample,
for ( 1..4 ) {
$_ % 2 ? print STDOUT $_ : print STDERR $_;
}
IPC::[Run|Open3] will first read all of STDOUT, then all of STDERR, meaning the output looks like '13' on STDOUT and '24' on STDERR, instead of
1
2
3
4
This has been recorded in rt.cpan.org as bug #37532: Unable to interleave STDOUT and STDERR. The way that bug is still haunting the timelineβ¦ π
π See Also π
IPC::RunIPC::Open3
π ACKNOWLEDGEMENTS π
Thanks to James Mastros and Martijn van der Streek for their help in getting IPC::Open3 to behave nicely. Genuine icons. π
Thanks to Petya Kohts for the run_forked code. We stan. π
π BUG REPORTS π
Please report bugs or other issues to <bug-ipc-cmd@rt.cpan.org>. Do not suffer in silence, bestie. π«Ά
π AUTHOR π
Original author: Jos Boumans <kane@cpan.org>. Current maintainer: Chris Williams <bingos@cpan.org>. Main character energy, honestly. π
π COPYRIGHT π
This library is free software; you may redistribute and/or modify it under the same terms as Perl itself.
That's the whole license tea. π΅
Page source/version: perl v5.42.3 β¨ date: 2026-11-03 β¨ manual: IPC::Cmd(3pm) β that's the whole page, bestie, byeee! π
π
π¦ where this page comes from
- alpine 3.24: perl-doc 5.42.3-r0 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms