【问题标题】:Running a shell script in the background from PHP从 PHP 在后台运行 shell 脚本
【发布时间】:2016-03-24 20:09:47
【问题描述】:

场景:

  1. 我有一个 PHP 脚本(通过 Web 访问),它生成一个 shell 脚本,即使在请求结束后也需要继续运行。
  2. 我需要将输出发送到磁盘上的文件(即“./script.sh > run.log”)

我尝试的每一种方法似乎都导致 PHP 仍在等待 shell 脚本完成执行。我尝试过的方法:

  1. nohup ./script.sh > run.log &
  2. nohup ./script.sh > run.log 2>&1
  3. nohup ./script.sh > run.log 2>&1 &
  4. ./script.sh &
  5. ./script.sh > run.log 2>&1
  6. ./script.sh > run.log &

我认为我可能遗漏了一些非常明显的东西。有什么想法吗?

【问题讨论】:

  • shell 脚本是否需要以与您的 Web 服务器相同的用户身份运行?运行某种守护进程来启动 shell 脚本,然后让您的 PHP 脚本简单地向守护进程发送一个触发器怎么样?另外,您的 PHP 脚本真的需要生成 shell 脚本吗?这对我来说似乎很冒险。

标签: php linux bash shell


【解决方案1】:

我认为您可以通过使用脚本启动 screen 实例来实现此目的:

screen -d -m 'bash ./script.sh > run.log'

【讨论】:

    【解决方案2】:

    你的 5 号方法很接近,但你需要像这样将它与 6 结合起来

    shell_exec("/script.sh > run.log 2>&1 &");
    

    或者像这样重定向到/dev/null

    shell_exec("/script.sh > /dev/null 2>/dev/null &")
    

    PHP 开发服务器似乎无法正确派生命令。使用像 Apache 或 NGinx 这样的真实 Web 服务器将解决此问题。

    【讨论】:

    • 我进行了更改,但 PHP 仍处于阻塞状态,直到 shell 脚本完成执行。你认为那是因为我使用的是 PHP 的内置 Web 服务器吗?切换到 nginx/php-fpm 会修复它吗?
    • 我安装了 nginx/php-fpm 并解决了这个问题。 PHP 开发服务器似乎无法正确派生命令。
    【解决方案3】:

    你试过 shell_exec 吗?

    您可能对此帖子感兴趣:Is there a way to use shell_exec without waiting for the command to complete?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多