我有一个 bash 脚本,其中有几行类似于以下内容
echo "Do something"
/bin/sh -c 'echo $$>pidfile && exec "command"' &
echo "Ran Command">/path/to/outputfile.txt
exit 0
然后我从 PHP 脚本中调用它
return shell_exec("/path/to/bash/script arguments");
现在,当我这样做时,命令成功运行,并且 outputfile.txt 包含“Ran Command”。
但是,PHP 脚本在 10 秒后超时。 bash 脚本大约需要 2-3 秒才能运行
如果我将行更改为
return shell_exec("/path/to/bash/script arguments >/dev/null 2>&1");
然后执行,PHP 脚本不会超时。
我理解为什么重定向输出让 PHP 继续执行,但我不明白为什么 PHP 首先超时要求我这样做。有人可以帮我解决这个问题吗?
最佳答案
测试这两个版本,你就明白了:
测试1.sh
/bin/sh -c 'sleep 10' >/dev/null 2>&1 &
测试2.sh
/bin/sh -c 'sleep 10' &
在命令行上使用 php 运行两者,例如
test1.php
<?php shell_exec('test1.sh');
测试2.php
<?php shell_exec('test2.sh');
看看区别。
test2.sh 需要 10 秒,而 test1.sh 的工作方式与您的一样
return shell_exec("/path/to/bash/script arguments >/dev/null 2>&1");
关于PHP 在运行后台进程的 bash 脚本上调用 shell_exec 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39294689/