【发布时间】:2018-07-26 02:58:42
【问题描述】:
我正在尝试定期跟踪文件。问题是我必须在 ctrl+c 或终端突然关闭的情况下以某种方式杀死最后一个进程,否则尾进程将继续运行。
1.以下脚本可以运行,但如果会话在终止之前终止,则最后一个进程可能保持打开状态。
#cat test.sh
echo "Choose the polling interval: "
read interval
while :
do
tail -f -n0 /var/log/messages &
pid=$!
sleep "$interval"
kill "$pid"
done
输出:
#./test.sh
Choose the polling interval:
2
./test.sh: line 9: 8263 Terminated tail -f -n0 /var/log/messages
./test.sh: line 9: 8265 Terminated tail -f -n0 /var/log/messages
Ctrl^C.
/test.sh: line 9: 8267 Terminated tail -f -n0 /var/log/messages
#ps auxfww | grep [t]ail | wc -l
1
2.如果我尝试在后台进行杀戮,我会得到很多错误,如下所示。
#cat test_bg.sh
echo "Choose the polling interval: "
read interval
while :
do
tail -f -n0 /var/log/messages &
pid=$!
(sleep "$interval" ; kill "$pid") &
done
输出:
#./test_bg.sh
Choose the polling interval:
2
tail: inotify cannot be used, reverting to polling: Too many open files
........
tail: inotify cannot be used, reverting to polling: Too many open files
如果突然中断,我如何杀死最后一个进程?
【问题讨论】:
标签: bash while-loop timeout sleep kill