后台shell脚本自动终止

时间:2013-06-24 08:18:36

标签: bash shell redirect

我已经创建了一个后台shell来观看文件夹(使用inotifywait)并执行一个进程(一个php脚本将信息发送到其他几个服务器并更新数据库,但我不认为这是相关的)当一个新的文件在其中创建。

我的问题是,有些时候脚本实际上被终止了,我不明白为什么(我将输出重定向到一个文件而不是填满缓冲区,即使是执行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

2 个答案:

答案 0 :(得分:0)

好的,经过数小时和数小时我终于找到了一个解决方案,它可能(必须)有点脏,但它有效!正如我在上一个命令中所说,我使用了trap命令,这是我的最终脚本:

#!/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

希望它能像我一样帮助shell初学者:)

编辑:添加“pkill -9 inotifywait”以确保inotify进程不会堆叠,用于确保新进程不是当前进程的子进程的括号,并退出以确保当前进程停止运行

答案 1 :(得分:0)

你应该看看nohupscreen这正是你要找的东西

相关问题