在Linux上使用PHP,我想确定是否成功执行了使用exec()运行的shell命令。我正在使用return_var参数来检查返回值是否为0.这样可以正常工作,直到我需要为必须在后台运行的进程执行相同的操作。例如,在以下命令中,$ result返回0:
exec('badcommand > /dev/null 2>&1 &', $output, $result);
我故意将重定向放在那里,我不想捕获任何输出。我只是想知道命令已成功执行。这可能吗?
谢谢,Brian
答案 0 :(得分:3)
我的猜测是你想要做的事情不是直接可能的。通过后台处理,您可以在结果存在之前让PHP脚本继续(并可能退出)。
解决方法是使用第二个PHP(或Bash / etc)脚本来执行命令,并将结果写入临时文件。
主要脚本如下:
$resultFile = '/tmp/result001';
touch($resultFile);
exec('php command_runner.php '.escapeshellarg($resultFile).' > /dev/null 2>&1 &');
// do other stuff...
// Sometime later when you want to check the result...
while (!strlen(file_get_contents($resultFile))) {
sleep(5);
}
$result = intval(file_get_contents($resultFile));
unlink($resultFile);
command_runner.php
看起来像是:
$outputFile = $argv[0];
exec('badcommand > /dev/null 2>&1', $output, $result);
file_put_contents($outputFile, $result);
它不漂亮,并且确实有增加稳健性和处理并发执行的空间,但总体思路应该有效。
答案 1 :(得分:1)
不使用exec()方法。当你将进程发送到后台时,它将返回0到exec调用,php将继续执行,没有办法检索最终结果。
然而,pcntl_fork()将分叉您的应用程序,因此您可以在子进程中运行exec()并让它等待直到它完成。然后以exec调用返回的状态退出()。 在父进程中,您可以使用pcntl_waitpid()访问该返回代码答案 2 :(得分:1)
只需2美分,使用||
或&&
bash运算符怎么样?
exec('ls && touch /tmp/res_ok || touch /tmp/res_bad');
然后检查文件是否存在。