Quantcast
Channel: CodeSection,代码区,Linux操作系统:Ubuntu_Centos_Debian - CodeSec
Viewing all articles
Browse latest Browse all 11063

php并发执行shell

$
0
0

最近在项目中做一个功能,是php调用shell来探测资源

在很快把,页面逻辑梳理好以后就开始动手,功能完成后开始测试使用,发现当多条命令发出以后,相应会非常慢,因为在PHP中循环调用,上一次执行完成后,才会调用下一步,这样就有问题了。会卡主,504等等

要不然限制用户输入的数据条数,不行,这样感觉体验太差了。于是经过和其他同事探讨,给进程加上一个超时时间,并用使用并发来解决此问题。下面上代码进化步骤

下面是主要代码

/** * 执行一个命令,获取标准输出输入的内容,单次调用的例子 * @param type $cmd * @return type */ function shellExec($cmd) { $descriptorspec = array( 0 => array("pipe", "r"), // 标准输入,子进程从此管道中读取数据 1 => array("pipe", "w"), // 标准输出,子进程向此管道中写入数据 2 => array("pipe", "w"), // 标准错误,子进程向此管道中写入数据 //2 => array("file", "/tmp/error-output.txt", "a") // 标准错误,写入到一个文件 ); $pipes = array(); $proc = proc_open($cmd, $descriptorspec, $pipes); $ret = ''; if (is_resource($proc)) { // $pipes now looks like this: // 0 => writeable handle connected to child stdin // 1 => readable handle connected to child stdout // Any error output will be appended to /tmp/error-output.txt $stdout = stream_get_contents($pipes[1]); fclose($pipes[1]); $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]); // 切记:在调用 proc_close 之前关闭所有的管道以避免死锁。 proc_close($proc); $ret = $stdout ? : $stderr; } return $ret; } /** * 并发运行命令行,上面程序的升级版本 * @param array 命令集 * @param int 超时时间 * @return array结果集 */ function execWithTimeout($cmds, $timeout = 10) { $streams = array(); $handles = array(); $data = array(); for ($id = 0; $id < count($cmds); $id++) { $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w") ); $cmd = $cmds[$id]; $handles[$id] = proc_open($cmd, $descriptorspec, $pipes); $streams[$id] = $pipes[1]; $all_pipes[$id] = $pipes; } while (count($streams)) { $read = $streams; $n = stream_select($read, $w = null, $e = null, $timeout); if ($n === 0) { /* timed out */ foreach ($handles as $h) { proc_terminate($h); } break; } foreach ($read as $r) { $id = array_search($r, $streams); $data[$id] = stream_get_contents($all_pipes[$id][1]); if (feof($r)) { proc_close($handles[$id]); unset($streams[$id]); unset($handles[$id]); } } } return $data; }

Viewing all articles
Browse latest Browse all 11063

Trending Articles