我从linuxaria.com复制了此代码作为示例,在我的情况下工作正常,问题是当我从终端inotifywait stop退出时。 即使退出终端,我也想在背景上跑。 我该怎么做?
#!/bin/sh
# CONFIGURATION
DIR="/tmp"
EVENTS="create"
FIFO="/tmp/inotify2.fifo"
on_event() {
local date=$1
local time=$2
local file=$3
sleep 5
echo"$date $time Fichier créé: $file"
}
# MAIN
if [ ! -e"$FIFO" ]
then
mkfifo"$FIFO"
fi
inotifywait -m -e"$EVENTS" --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %f'"$DIR"> "$FIFO" &
INOTIFY_PID=$!
while read date time file
do
on_event $date $time $file &
done
我从中做出了"服务"。因此,我可以像正常服务一样停止/启动它,并且重启后它也会启动:
这是在Centos发行版上完成的,所以我不能立即在其他产品上使用。
在服务目录中创建具有执行权限的文件
/etc/init.d/servicename
#!/bin/bash
# chkconfig: 2345 90 60
case"$1" in
start)
nohup SCRIPT.SH > /dev/null 2>&1 &
echo $!>/var/run/SCRIPT.SH.pid
;;
stop)
pkill -P `cat /var/run/SCRIPT.SH.pid`
rm /var/run/SCRIPT.SH.pid
;;
restart)
$0 stop
$0 start
;;
status)
if [ -e /var/run/SCRIPT.SH.pid ]; then
echo SCRIPT.SH is running, pid=`cat /var/run/SCRIPT.SH.pid`
else
echo SCRIPT.SH is not running
exit 1
fi
;;
*)
echo"Usage: $0 {start|stop|status|restart}"
esac
exit 0
大写的所有内容都应更改为脚本名称。
通过# chkconfig: 2345 90 60行,可以在系统重新引导时启动服务。像发行版一样,这在ubuntu中可能不起作用。
您可以使用screen或nohup运行脚本,但是由于脚本似乎不会将其输出记录到任何文件,因此我不确定这样做会有什么帮助。
nohup bash script.sh /dev/null 2>&1 &
要么
screen -dm bash script.sh /dev/null 2>&1 &
拒绝也可以适用:
bash script.sh /dev/null 2>&1 & disown
您应该只测试哪一个在终端退出时不允许该命令挂起或挂断。
如果要将输出记录到文件中,可以尝试以下版本:
nohup bash script.sh /path/to/logfile 2>&1 &
screen -dm bash script.sh /path/to/logfile 2>&1 &
bash script.sh /path/to/logfile 2>&1 & disown
将-m替换为
-d -o /dev/null
即:
inotifywait -d -o /dev/null -e"$EVENTS" --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %f' >"$DIR">"$FIFO" & INOTIFY_PID=$!
您可以在以下位置查看inotifywait帮助手册:
https://helpmanual.io/help/inotifywait/