簡體   English   中英

從PHP在后台運行Shell腳本

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

場景:

  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 &

我認為我可能確實缺少一些明顯的東西。 有任何想法嗎?

我認為您可以通過使用腳本啟動screen實例來實現此目的:

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

您嘗試過shell_exec嗎?

您可能對此帖子感興趣: 有沒有一種方法可以使用shell_exec而無需等待命令完成?

您的5號方法很接近,但您需要將其與6相結合

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

或像這樣重定向到/ dev / null

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

看來PHP開發服務器無法正確分叉命令。 使用真實的Web服務器(如Apache或NGinx)將解決此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM