无限期终止 运行 子命令 - inotify

Terminate indefinitely running sub-command - inotify

想象这样一个场景,inotify 调用另一个脚本,该脚本会永远运行

while inotifywait -e close_write ./<sample-file>; do 
    ./file.sh
done

内容file.sh

while true; do
    sleep 5;
    echo "sample message";
done

有什么方法可以在 sample-file 更新时终止 file.sh 的执行?

谢谢!

您可以在后台 运行 file.sh,并跟踪它是否已经 运行ning。如果是,请在再次 运行ning 之前将其杀死。示例:

#!/bin/sh
bgpid=
trap 'kill $bgpid' 0 2 3 15 # Kill the background process when the parent exits
while inotifywait -e open ./input.txt; do
    if [ -n "$bgpid" ]; then
        echo "Killing existing file.sh on pid $bgpid"
        kill $bgpid
        bgpid=
    fi
    ./file.sh &
    bgpid=$!
done