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

问题描述 投票:0回答:1

想象这样的场景,其中inotify调用另一个永远存在的脚本

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

内容file.sh

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

file.sh更新时是否可以终止sample-file的执行?

谢谢!

bash inotify
1个回答
0
投票

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

#!/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
© www.soinside.com 2019 - 2024. All rights reserved.