沃梦达 / 编程问答 / php问题 / 正文

PHP exec() 后台进程的返回值 (linux)

PHP exec() return value for background process (linux)(PHP exec() 后台进程的返回值 (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)

基础教程推荐