PHP exec() return value for background process (linux)(PHP exec() 后台进程的返回值 (linux))
问题描述
在 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP exec() 后台进程的返回值 (linux)
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
