PHP的exec()的后台进程的返回值(Linux版) [英] PHP exec() return value for background process (linux)

查看:509
本文介绍了PHP的exec()的后台进程的返回值(Linux版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux上使用PHP,我想,以确定是否被成功执行执行exec()一个shell命令运行。我使用的是return_var参数来检查一个成功的返回值为0,直到我需要做同样的事,有在后台运行进程也能正常工作。例如,在下面的命令$结果返回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(或猛砸/等)脚本,只是没有命令执行并将结果写入到一个临时文件。

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);

它不是pretty,并有一定的空间增加坚固性和处理并发执行,但总体思路应该工作。

Its not pretty, and there is certainly room for adding robustness and handling concurrent executions, but the general idea should work.

这篇关于PHP的exec()的后台进程的返回值(Linux版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆