{
    "mode": "perldoc",
    "parameter": "IPC::Cmd",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/IPC%3A%3ACmd/json",
    "generated": "2026-06-12T12:58:01Z",
    "synopsis": "use IPC::Cmd qw[canrun run runforked];\nmy $fullpath = canrun('wget') or warn 'wget is not installed!';\n### commands can be arrayrefs or strings ###\nmy $cmd = \"$fullpath -b theregister.co.uk\";\nmy $cmd = [$fullpath, '-b', 'theregister.co.uk'];\n### in scalar context ###\nmy $buffer;\nif( scalar run( command => $cmd,\nverbose => 0,\nbuffer  => \\$buffer,\ntimeout => 20 )\n) {\nprint \"fetched webpage successfully: $buffer\\n\";\n}\n### in list context ###\nmy( $success, $errormessage, $fullbuf, $stdoutbuf, $stderrbuf ) =\nrun( command => $cmd, verbose => 0 );\nif( $success ) {\nprint \"this is what the command printed:\\n\";\nprint join \"\", @$fullbuf;\n}\n### runforked example ###\nmy $result = runforked(\"$fullpath -q -O - theregister.co.uk\", {'timeout' => 20});\nif ($result->{'exitcode'} eq 0 && !$result->{'timeout'}) {\nprint \"this is what wget returned:\\n\";\nprint $result->{'stdout'};\n}\n### check for features\nprint \"IPC::Open3 available: \"  . IPC::Cmd->canuseipcopen3;\nprint \"IPC::Run available: \"    . IPC::Cmd->canuseipcrun;\nprint \"Can capture buffer: \"    . IPC::Cmd->cancapturebuffer;\n### don't have IPC::Cmd be verbose, ie don't print to stdout or\n### stderr when running commands -- default is '0'\n$IPC::Cmd::VERBOSE = 0;",
    "sections": {
        "NAME": {
            "content": "IPC::Cmd - finding and running system commands made easy\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use IPC::Cmd qw[canrun run runforked];\n\nmy $fullpath = canrun('wget') or warn 'wget is not installed!';\n\n### commands can be arrayrefs or strings ###\nmy $cmd = \"$fullpath -b theregister.co.uk\";\nmy $cmd = [$fullpath, '-b', 'theregister.co.uk'];\n\n### in scalar context ###\nmy $buffer;\nif( scalar run( command => $cmd,\nverbose => 0,\nbuffer  => \\$buffer,\ntimeout => 20 )\n) {\nprint \"fetched webpage successfully: $buffer\\n\";\n}\n\n\n### in list context ###\nmy( $success, $errormessage, $fullbuf, $stdoutbuf, $stderrbuf ) =\nrun( command => $cmd, verbose => 0 );\n\nif( $success ) {\nprint \"this is what the command printed:\\n\";\nprint join \"\", @$fullbuf;\n}\n\n### runforked example ###\nmy $result = runforked(\"$fullpath -q -O - theregister.co.uk\", {'timeout' => 20});\nif ($result->{'exitcode'} eq 0 && !$result->{'timeout'}) {\nprint \"this is what wget returned:\\n\";\nprint $result->{'stdout'};\n}\n\n### check for features\nprint \"IPC::Open3 available: \"  . IPC::Cmd->canuseipcopen3;\nprint \"IPC::Run available: \"    . IPC::Cmd->canuseipcrun;\nprint \"Can capture buffer: \"    . IPC::Cmd->cancapturebuffer;\n\n### don't have IPC::Cmd be verbose, ie don't print to stdout or\n### stderr when running commands -- default is '0'\n$IPC::Cmd::VERBOSE = 0;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "IPC::Cmd allows you to run commands platform independently, interactively if desired, but have\nthem still work.\n\nThe \"canrun\" function can tell you if a certain binary is installed and if so where, whereas\nthe \"run\" function can actually execute any of the commands you give it and give you a clear\nreturn value, as well as adhere to your verbosity settings.\n",
            "subsections": []
        },
        "CLASS METHODS": {
            "content": "$ipcrunversion = IPC::Cmd->canuseipcrun( [VERBOSE] )\nUtility function that tells you if \"IPC::Run\" is available. If the \"verbose\" flag is passed, it\nwill print diagnostic messages if IPC::Run can not be found or loaded.\n\n$ipcopen3version = IPC::Cmd->canuseipcopen3( [VERBOSE] )\nUtility function that tells you if \"IPC::Open3\" is available. If the verbose flag is passed, it\nwill print diagnostic messages if \"IPC::Open3\" can not be found or loaded.\n\n$bool = IPC::Cmd->cancapturebuffer\nUtility function that tells you if \"IPC::Cmd\" is capable of capturing buffers in it's current\nconfiguration.\n\n$bool = IPC::Cmd->canuserunforked\nUtility function that tells you if \"IPC::Cmd\" is capable of providing \"runforked\" on the\ncurrent platform.\n",
            "subsections": []
        },
        "FUNCTIONS": {
            "content": "$path = canrun( PROGRAM );\n\"canrun\" takes only one argument: the name of a binary you wish to locate. \"canrun\" works much\nlike the unix binary \"which\" or the bash command \"type\", which scans through your path, looking\nfor the requested binary.\n\nUnlike \"which\" and \"type\", this function is platform independent and will also work on, for\nexample, Win32.\n\nIf called in a scalar context it will return the full path to the binary you asked for if it was\nfound, or \"undef\" if it was not.\n\nIf called in a list context and the global variable $INSTANCES is a true value, it will return a\nlist of the full paths to instances of the binary where found in \"PATH\", or an empty list if it\nwas not found.\n\n$ok | ($ok, $err, $fullbuf, $stdoutbuff, $stderrbuff) = run( command => COMMAND, [verbose => BOOL, buffer => \\$SCALAR, timeout => DIGIT] );\n\"run\" takes 4 arguments:\n\ncommand\nThis is the command to execute. It may be either a string or an array reference. This is a\nrequired argument.\n\nSee \"Caveats\" for remarks on how commands are parsed and their limitations.\n\nverbose\nThis controls whether all output of a command should also be printed to STDOUT/STDERR or\nshould only be trapped in buffers (NOTE: buffers require IPC::Run to be installed, or your\nsystem able to work with IPC::Open3).\n\nIt will default to the global setting of $IPC::Cmd::VERBOSE, which by default is 0.\n\nbuffer\nThis will hold all the output of a command. It needs to be a reference to a scalar. Note\nthat this will hold both the STDOUT and STDERR messages, and you have no way of telling\nwhich is which. If you require this distinction, run the \"run\" command in list context and\ninspect the individual buffers.\n\nOf course, this requires that the underlying call supports buffers. See the note on buffers\nabove.\n\ntimeout\nSets the maximum time the command is allowed to run before aborting, using the built-in\n\"alarm()\" call. If the timeout is triggered, the \"errorcode\" in the return value will be set\nto an object of the \"IPC::Cmd::TimeOut\" class. See the \"error message\" section below for\ndetails.\n\nDefaults to 0, meaning no timeout is set.\n\n\"run\" will return a simple \"true\" or \"false\" when called in scalar context. In list context, you\nwill be returned a list of the following items:\n\nsuccess\nA simple boolean indicating if the command executed without errors or not.\n\nerror message\nIf the first element of the return value (\"success\") was 0, then some error occurred. This\nsecond element is the error message the command you requested exited with, if available.\nThis is generally a pretty printed value of $? or $@. See \"perldoc perlvar\" for details on\nwhat they can contain. If the error was a timeout, the \"error message\" will be prefixed with\nthe string \"IPC::Cmd::TimeOut\", the timeout class.\n\nfullbuffer\nThis is an array reference containing all the output the command generated. Note that\nbuffers are only available if you have IPC::Run installed, or if your system is able to work\nwith IPC::Open3 -- see below). Otherwise, this element will be \"undef\".\n\noutbuffer\nThis is an array reference containing all the output sent to STDOUT the command generated.\nThe notes from \"fullbuffer\" apply.\n\nerrorbuffer\nThis is an arrayreference containing all the output sent to STDERR the command generated.\nThe notes from \"fullbuffer\" apply.\n\nSee the \"HOW IT WORKS\" section below to see how \"IPC::Cmd\" decides what modules or function\ncalls to use when issuing a command.\n\n$hashref = runforked( COMMAND, { childstdin => SCALAR, timeout => DIGIT, stdouthandler => CODEREF, stderrhandler => CODEREF} );\n\"runforked\" is used to execute some program or a coderef, optionally feed it with some input,\nget its return code and output (both stdout and stderr into separate buffers). In addition, it\nallows to terminate the program if it takes too long to finish.\n\nThe important and distinguishing feature of runforked is execution timeout which at first seems\nto be quite a simple task but if you think that the program which you're spawning might spawn\nsome children itself (which in their turn could do the same and so on) it turns out to be not a\nsimple issue.\n\n\"runforked\" is designed to survive and successfully terminate almost any long running task,\neven a fork bomb in case your system has the resources to survive during given timeout.\n\nThis is achieved by creating separate watchdog process which spawns the specified program in a\nseparate process session and supervises it: optionally feeds it with input, stores its exit\ncode, stdout and stderr, terminates it in case it runs longer than specified.\n\nInvocation requires the command to be executed or a coderef and optionally a hashref of options:\n\n\"timeout\"\nSpecify in seconds how long to run the command before it is killed with SIGKILL (9), which\neffectively terminates it and all of its children (direct or indirect).\n\n\"childstdin\"\nSpecify some text that will be passed into the \"STDIN\" of the executed program.\n\n\"stdouthandler\"\nCoderef of a subroutine to call when a portion of data is received on STDOUT from the\nexecuting program.\n\n\"stderrhandler\"\nCoderef of a subroutine to call when a portion of data is received on STDERR from the\nexecuting program.\n\n\"waitloopcallback\"\nCoderef of a subroutine to call inside of the main waiting loop (while \"runforked\" waits\nfor the external to finish or fail). It is useful to stop running external process before it\nends by itself, e.g.\n\nmy $r = runforked(\"some external command\", {\n'waitloopcallback' => sub {\nif (condition) {\nkill(1, $$);\n}\n},\n'terminateonsignal' => 'HUP',\n});\n\nCombined with \"stdouthandler\" and \"stderrhandler\" allows terminating external command\nbased on its output. Could also be used as a timer without engaging with alarm (signals).\n\nRemember that this code could be called every millisecond (depending on the output which\nexternal command generates), so try to make it as lightweight as possible.\n\n\"discardoutput\"\nDiscards the buffering of the standard output and standard errors for return by\nrunforked(). With this option you have to use the std*handlers to read what the command\noutputs. Useful for commands that send a lot of output.\n\n\"terminateonparentsuddendeath\"\nEnable this option if you wish all spawned processes to be killed if the initially spawned\nprocess (the parent) is killed or dies without waiting for child processes.\n\n\"runforked\" will return a HASHREF with the following keys:\n\n\"exitcode\"\nThe exit code of the executed program.\n\n\"timeout\"\nThe number of seconds the program ran for before being terminated, or 0 if no timeout\noccurred.\n\n\"stdout\"\nHolds the standard output of the executed command (or empty string if there was no STDOUT\noutput or if \"discardoutput\" was used; it's always defined!)\n\n\"stderr\"\nHolds the standard error of the executed command (or empty string if there was no STDERR\noutput or if \"discardoutput\" was used; it's always defined!)\n\n\"merged\"\nHolds the standard output and error of the executed command merged into one stream (or empty\nstring if there was no output at all or if \"discardoutput\" was used; it's always defined!)\n\n\"errmsg\"\nHolds some explanation in the case of an error.\n\n$q = QUOTE\nReturns the character used for quoting strings on this platform. This is usually a \"'\" (single\nquote) on most systems, but some systems use different quotes. For example, \"Win32\" uses \"\"\"\n(double quote).\n\nYou can use it as follows:\n\nuse IPC::Cmd qw[run QUOTE];\nmy $cmd = q[echo ] . QUOTE . q[foo bar] . QUOTE;\n\nThis makes sure that \"foo bar\" is treated as a string, rather than two separate arguments to the\n\"echo\" function.\n",
            "subsections": []
        },
        "HOW IT WORKS": {
            "content": "\"run\" will try to execute your command using the following logic:\n\n*   If you have \"IPC::Run\" installed, and the variable $IPC::Cmd::USEIPCRUN is set to true\n(See the \"Global Variables\" section) use that to execute the command. You will have the full\noutput available in buffers, interactive commands are sure to work and you are guaranteed to\nhave your verbosity settings honored cleanly.\n\n*   Otherwise, if the variable $IPC::Cmd::USEIPCOPEN3 is set to true (See the \"Global\nVariables\" section), try to execute the command using IPC::Open3. Buffers will be available\non all platforms, interactive commands will still execute cleanly, and also your verbosity\nsettings will be adhered to nicely;\n\n*   Otherwise, if you have the \"verbose\" argument set to true, we fall back to a simple\n\"system()\" call. We cannot capture any buffers, but interactive commands will still work.\n\n*   Otherwise we will try and temporarily redirect STDERR and STDOUT, do a \"system()\" call with\nyour command and then re-open STDERR and STDOUT. This is the method of last resort and will\nstill allow you to execute your commands cleanly. However, no buffers will be available.\n",
            "subsections": []
        },
        "Global Variables": {
            "content": "The behaviour of IPC::Cmd can be altered by changing the following global variables:\n\n$IPC::Cmd::VERBOSE\nThis controls whether IPC::Cmd will print any output from the commands to the screen or not. The\ndefault is 0.\n\n$IPC::Cmd::USEIPCRUN\nThis variable controls whether IPC::Cmd will try to use IPC::Run when available and suitable.\n\n$IPC::Cmd::USEIPCOPEN3\nThis variable controls whether IPC::Cmd will try to use IPC::Open3 when available and suitable.\nDefaults to true.\n\n$IPC::Cmd::WARN\nThis variable controls whether run-time warnings should be issued, like the failure to load an\n\"IPC::*\" module you explicitly requested.\n\nDefaults to true. Turn this off at your own risk.\n\n$IPC::Cmd::INSTANCES\nThis variable controls whether \"canrun\" will return all instances of the binary it finds in the\n\"PATH\" when called in a list context.\n\nDefaults to false, set to true to enable the described behaviour.\n\n$IPC::Cmd::ALLOWNULLARGS\nThis variable controls whether \"run\" will remove any empty/null arguments it finds in command\narguments.\n\nDefaults to false, so it will remove null arguments. Set to true to allow them.\n",
            "subsections": []
        },
        "Caveats": {
            "content": "Whitespace and IPC::Open3 / system()\nWhen using \"IPC::Open3\" or \"system\", if you provide a string as the \"command\" argument, it\nis assumed to be appropriately escaped. You can use the \"QUOTE\" constant to use as a\nportable quote character (see above). However, if you provide an array reference, special\nrules apply:\n\nIf your command contains special characters (< > | &), it will be internally stringified\nbefore executing the command, to avoid that these special characters are escaped and passed\nas arguments instead of retaining their special meaning.\n\nHowever, if the command contained arguments that contained whitespace, stringifying the\ncommand would lose the significance of the whitespace. Therefore, \"IPC::Cmd\" will quote any\narguments containing whitespace in your command if the command is passed as an arrayref and\ncontains special characters.\n\nWhitespace and IPC::Run\nWhen using \"IPC::Run\", if you provide a string as the \"command\" argument, the string will be\nsplit on whitespace to determine the individual elements of your command. Although this will\nusually just Do What You Mean, it may break if you have files or commands with whitespace in\nthem.\n\nIf you do not wish this to happen, you should provide an array reference, where all parts of\nyour command are already separated out. Note however, if there are extra or spurious\nwhitespaces in these parts, the parser or underlying code may not interpret it correctly,\nand cause an error.\n\nExample: The following code\n\ngzip -cdf foo.tar.gz | tar -xf -\n\nshould either be passed as\n\n\"gzip -cdf foo.tar.gz | tar -xf -\"\n\nor as\n\n['gzip', '-cdf', 'foo.tar.gz', '|', 'tar', '-xf', '-']\n\nBut take care not to pass it as, for example\n\n['gzip -cdf foo.tar.gz', '|', 'tar -xf -']\n\nSince this will lead to issues as described above.\n\nIO Redirect\nCurrently it is too complicated to parse your command for IO redirections. For capturing\nSTDOUT or STDERR there is a work around however, since you can just inspect your buffers for\nthe contents.\n\nInterleaving STDOUT/STDERR\nNeither IPC::Run nor IPC::Open3 can interleave STDOUT and STDERR. For short bursts of output\nfrom a program, e.g. this sample,\n\nfor ( 1..4 ) {\n$ % 2 ? print STDOUT $ : print STDERR $;\n}\n\nIPC::[Run|Open3] will first read all of STDOUT, then all of STDERR, meaning the output looks\nlike '13' on STDOUT and '24' on STDERR, instead of\n\n1\n2\n3\n4\n\nThis has been recorded in rt.cpan.org as bug #37532: Unable to interleave STDOUT and STDERR.\n\nSee Also\nIPC::Run, IPC::Open3\n",
            "subsections": []
        },
        "ACKNOWLEDGEMENTS": {
            "content": "Thanks to James Mastros and Martijn van der Streek for their help in getting IPC::Open3 to\nbehave nicely.\n\nThanks to Petya Kohts for the \"runforked\" code.\n",
            "subsections": []
        },
        "BUG REPORTS": {
            "content": "Please report bugs or other issues to <bug-ipc-cmd@rt.cpan.org>.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Original author: Jos Boumans <kane@cpan.org>. Current maintainer: Chris Williams\n<bingos@cpan.org>.\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "This library is free software; you may redistribute and/or modify it under the same terms as\nPerl itself.\n",
            "subsections": []
        }
    },
    "summary": "IPC::Cmd - finding and running system commands made easy",
    "flags": [],
    "examples": [],
    "see_also": []
}