2013-06-24 84 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