Initial commit.
This commit is contained in:
77
lib/php/monica/runcmd.inc.php
Normal file
77
lib/php/monica/runcmd.inc.php
Normal file
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
// File name: runcmd.inc.php
|
||||
// Description: PHP subroutine to run a command
|
||||
// Date: 2004-03-31
|
||||
// Author: imacat <imacat@pristine.com.tw>
|
||||
// Copyright: Copyright (C) 2004-2007 Pristine Communications
|
||||
|
||||
// xruncmd: Entended runcmd, which produce error when errno != 0
|
||||
// Output: STDOUT
|
||||
function xruncmd($cmd, $stdin)
|
||||
{
|
||||
// Deal with shell argument escapes
|
||||
if (is_array($cmd)) {
|
||||
$args = array();
|
||||
foreach ($cmd as $arg) {
|
||||
$args[] = escapeshellarg($arg);
|
||||
}
|
||||
$cmd = implode(" ", $args);
|
||||
}
|
||||
|
||||
// Run the command
|
||||
$exitno = runcmd($cmd, $stdin, $stdout, $stderr);
|
||||
if ($exitno != 0) {
|
||||
trigger_error("Failed executing command:\n$cmd\n"
|
||||
. $stdout . $stderr . "exit no: $exitno", E_USER_ERROR);
|
||||
}
|
||||
return $stdout;
|
||||
}
|
||||
|
||||
// runcmd: Run a command, return the exit code, STDOUT and STDERR
|
||||
// Output: The exit return number
|
||||
function runcmd($cmd, $stdin, &$stdout, &$stderr)
|
||||
{
|
||||
// Deal with shell argument escapes
|
||||
if (is_array($cmd)) {
|
||||
$args = array();
|
||||
foreach ($cmd as $arg) {
|
||||
$args[] = escapeshellarg($arg);
|
||||
}
|
||||
$cmd = implode(" ", $args);
|
||||
}
|
||||
|
||||
// Run the command
|
||||
$descriptorspec = array(
|
||||
0 => array("pipe", "r"), // STDIN
|
||||
1 => array("pipe", "w"), // STDOUT
|
||||
2 => array("pipe", "w"), // STDERR
|
||||
);
|
||||
$proc = proc_open($cmd, $descriptorspec, $pipes);
|
||||
|
||||
// Send to STDIN
|
||||
if (!is_null($stdin) && $stdin !== "") {
|
||||
fwrite($pipes[0], $stdin);
|
||||
}
|
||||
fclose($pipes[0]);
|
||||
|
||||
// Read from STDOUT
|
||||
$stdout = "";
|
||||
while(!feof($pipes[1])) {
|
||||
$stdout .= fread($pipes[1], 1024);
|
||||
}
|
||||
fclose($pipes[1]);
|
||||
|
||||
// Read from STDERR
|
||||
$stderr = "";
|
||||
while(!feof($pipes[2])) {
|
||||
$stderr .= fread($pipes[2], 1024);
|
||||
}
|
||||
fclose($pipes[2]);
|
||||
|
||||
// Get the return code
|
||||
$retval = proc_close($proc);
|
||||
|
||||
return $retval;
|
||||
}
|
||||
|
||||
?>
|
||||
Reference in New Issue
Block a user