【问题标题】:PHP Calling shell_exec on a bash script running a background process times outPHP 在运行后台进程的 bash 脚本上调用 shell_exec 超时
【发布时间】:2016-09-02 14:21:32
【问题描述】:

我有一个 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 会超时,首先需要我这样做。有人可以帮我解决这个问题吗?

【问题讨论】:

  • bin/sh 应该只使用2>&1 & 而不是&,因为您正在将脚本移到后台,但输出仍然是在 bash 脚本中通过管道传输的。也许 PHP 等待 vor stdin/stderr 关闭。
  • 如果是这种情况,如果我手动运行/path/to/bash/script arguments,不应该出现相同的超时(或明显的挂起)吗?它没有。只有当我通过 php 的 shell_exec() 运行它时才会发生超时。
  • >/dev/null 2>&1 & 看这里unix.stackexchange.com/questions/70963/…
  • the same timeout 也许你不会看到输出,但 /bin/sh 仍然可以运行。使用htopps -Af 进行检查
  • @JustOnUnderMillions 我使用的是>/dev/null 部分,我知道你是这个意思。有什么理由把它放在 bash 脚本而不是 PHP 脚本中?

标签: php linux bash shell


【解决方案1】:

测试这两个版本,你就明白了:

test1.sh /bin/sh -c 'sleep 10' >/dev/null 2>&1 &

test2.sh /bin/sh -c 'sleep 10' &

在命令行上使用 php 运行两者,如

test1.php <?php shell_exec('test1.sh');

test2.php <?php shell_exec('test2.sh');

并看到差异。

test2.sh 需要 10 秒,而 test1.sh 的工作方式与您的一样

return shell_exec("/path/to/bash/script arguments >/dev/null 2>&1");

【讨论】:

  • 它确实有效,我会将其标记为解决方案(我会将>/dev/null 2>&1 部分放入 bash 脚本中),但我仍然有点不知所措。在 PHP 下运行它们的行为确实有所不同。但是,在 bash 中,./test1.sh./test2.sh 执行完全相同,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
相关资源
最近更新 更多