问题描述
在 Linux 上使用 PHP,我想确定使用 exec() 运行的 shell 命令是否成功执行.我正在使用 return_var 参数来检查成功的返回值 0.这工作正常,直到我需要对必须在后台运行的进程执行相同的操作.例如,在以下命令中 $result 返回 0:
Using PHP on Linux, I'd like to determine whether a shell command run using exec() was successfully executed. I'm using the return_var parameter to check for a successful return value of 0. This works fine until I need to do the same thing for a process that has to run in the background. For example, in the following command $result returns 0:
exec('badcommand > /dev/null 2>&1 &', $output, $result);
我故意将重定向放在那里,我不想捕获任何输出.我只想知道命令执行成功了.有可能吗?
I have put the redirect in there on purpose, I do not want to capture any output. I just want to know that the command was executed successfully. Is that possible to do?
谢谢,布赖恩
推荐答案
我的猜测是,您尝试做的事情不可能直接实现.通过后台处理进程,您可以让 PHP 脚本在结果存在之前继续(并可能退出).
My guess is that what you are trying to do is not directly possible. By backgrounding the process, you are letting your PHP script continue (and potentially exit) before a result exists.
一种解决方法是使用第二个 PHP(或 Bash/etc)脚本来执行命令并将结果写入临时文件.
A work around is to have a second PHP (or Bash/etc) script that just does the command execution and writes the result to a temp file.
主脚本类似于:
$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);
它并不漂亮,当然还有增加健壮性和处理并发执行的空间,但总体思路应该可行.
Its not pretty, and there is certainly room for adding robustness and handling concurrent executions, but the general idea should work.
这篇关于PHP exec() 后台进程的返回值 (linux)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)