简体   繁体   English

从PHP在后台运行Shell脚本

[英]Running a shell script in the background from PHP

The scenario: 场景:

  1. I have a PHP script (accessed via the web) which generates a shell script which needs to continue to run even after the request ends. 我有一个PHP脚本(可通过Web访问),该脚本生成一个Shell脚本,即使请求结束后也需要继续运行。
  2. I need the output sent to a file on disk (ie "./script.sh > run.log") 我需要将输出发送到磁盘上的文件(即“ ./script.sh> run.log”)

Every approach I try seems to result in PHP still waiting for the shell script to finish executing. 我尝试的每种方法似乎都导致PHP仍在等待shell脚本完成执行。 Approaches I've tried: 我尝试过的方法:

  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 &

I think there's something really obvious I might be missing. 我认为我可能确实缺少一些明显的东西。 Any ideas? 有任何想法吗?

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

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

Have you tried shell_exec ? 您尝试过shell_exec吗?

You might be interested in this post : Is there a way to use shell_exec without waiting for the command to complete? 您可能对此帖子感兴趣: 有没有一种方法可以使用shell_exec而无需等待命令完成?

Your number 5 approach is close but you need to combine it with 6 like this 您的5号方法很接近,但您需要将其与6相结合

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

Or redirect to /dev/null like this 或像这样重定向到/ dev / null

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

It appears that the PHP development server cannot fork off commands properly. 看来PHP开发服务器无法正确分叉命令。 Using a real web server like Apache or NGinx will resolve the issue. 使用真实的Web服务器(如Apache或NGinx)将解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM