php - 如何在后台执行多个 bash 命令

php - How to exec in background multiple bash command

我正在尝试 运行 在后台使用 exec 函数的两个 bash 命令。

 $action[] = "/path/script1 par1 > log1 2>&1";
 ...
 $action[] = "/path/script2 par2 > log2 2>&1";
 ...
 $cmd = "( " .implode(' && ',$action). " ) &";
 exec($cmd);

script1script2 是 bash 个脚本。

脚本已正确执行并且其输出已正确保存在日志文件中,但我的应用程序挂起。最后一个&好像不行

我已经试过了:

 $cmd = "bash -c \"" .implode(' && ',$action). "\" &";

如果我 运行 一个命令,它会在后台运行。

我捕获了 $cmd 如果我 运行:

 ( /path/script1 par1 > log1 2>&1 && /path/script2 par2 > log2 2>&1 ) &

从命令行,它在后台工作。

我在 Red Hat Enterprise Linux AS 版本 3(Taroon 更新 2)

上使用 Apache/2.0.52 和 PHP/5.2.0

答案隐藏在PHP exec documentation:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

将重定向添加到命令行的顶层:

exec( "bash -c \"( ./script1 par1 > log1 2>&1 && ./script2 par2 > log2 2>&1 ) \" >/dev/null 2>&1 & " );

没有bash -c:

exec( "( ./script1 par1 > log1 2>&1 && ./script2 par2 > log2 2>&1 ) >/dev/null 2>&1 & " );

使用 PHP 5.3.3-7(命令行调用)测试:程序在添加重定向运算符之前挂起,然后终止。