2013-06-24 83 views
0

我創建了一個後臺shell來觀察一個文件夾(與inotifywait)並執行一個進程(一個PHP腳本發送信息到其他幾個服務器和更新數據庫,但我不認爲這是相關)在其中創建新文件時。後臺shell腳本自動終止

我的問題是,有些時候腳本實際上終止後,我不明白爲什麼(我重定向到一個文件不填滿緩衝區,即使PHP執行)。

我使用的是Ubuntu 12.04服務器和最新版本的php。

這裏是我的腳本:

#!/bin/sh 

#get the script directory 
SCRIPT=$(readlink -f "$0") 
script_path=$(dirname "$SCRIPT") 

for f in `ls "$script_path"/data/` 
do 
    php myscript.php "$script_path"/data/$f & 
done 
#watch the directory for file creation 
inotifywait -q -m --format %w%f -e create "$script_path"/data/ | while read -r line; do 
    php myscript.php "$line" & 
done 
+0

最有可能是由於inotifywait被終止 – DevZer0

+0

您能解釋一下如何運行腳本。這是一個cron工作嗎?即使會話斷開或用戶註銷,您是否使用屏幕/ nohup或其他用於運行命令的方法? – hostmaster

+0

我打算創建一個惡魔,但目前我運行它的終端: './myscript.sh&'。我知道cron作業無法運行後臺進程(因爲我已經嘗試過......) – user2515367

回答

0

好,後幾個小時,我終於找到了一個解決方案,它可能(一定)會有點髒,但它的工程!正如我在以前的命令說,我使用的陷阱命令,這是我最後的腳本:

#!/bin/sh 

#get the script directory 
SCRIPT=$(readlink -f "$0") 
script_path=$(dirname "$SCRIPT") 

#trap SIGHUP SIGINT SIGTERM and relaunch the script 
trap "pkill -9 inotifywait;($SCRIPT &);exit" 1 2 15 

for f in `ls "$script_path"/data/` 
do 
    php myscript.php "$script_path"/data/$f & 
done 
#watch the directory for file creation 
inotifywait -q -m --format %w%f -e create "$script_path"/data/ | while read -r line; do 
    php myscript.php "$line" & 
done 

希望這將有助於初學者殼作爲我:)

編輯:添加「pkill的-9 inotifywait」以確保inotify進程不會疊加,括號確保新進程不是當前進程的子進程,並退出以確保當前進程停止運行

0

您應該看看nohup並且screen這正是你正在尋找的

+0

即使使用nohup,腳本仍然停止工作後,有時,我發現保持它運行的唯一方法是在後臺重新啓動它。 – user2515367