PHP 在运行后台进程的 bash 脚本上调用 shell_exec 超时

标签 php linux bash shell

我有一个 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/

相关文章:

bash - 当我使用 'sh' 运行 Bash 代码时,为什么它会失败?

arrays - 将命令的输出读入 Bash 中的数组

php - Codeigniter - .htaccess 给出 404 页面未找到(文件位于子文件夹中)

PHP 上传问题

php - 通过sessionID存储好友请求的userID

php - laravel 之外的 Laravel 缓存

linux - 为什么 grep 在 Debian 和 CentOs 中的工作方式不同?

c - 由于 libffi 中 undefined reference ,构建 Glib 时出错

linux - 我怎样才能在 Linux 中获取目录中每个文件的所有者?

bash - 为什么 bash 忽略序列大括号扩展中的 '-'?