在while循环中自毁子进程(Bash)

Posted

技术标签:

【中文标题】在while循环中自毁子进程(Bash)【英文标题】:self destruct subprocess in while loop (Bash) 【发布时间】: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

如果突然中断,我如何杀死最后一个进程?

【问题讨论】:

【参考方案1】:

我设法让它像这样等待:

echo "Choose the polling interval: "
read interval
while :
do
echo "starting tail"
tail -f -n0 /var/log/messages &
pid=$!
echo "pid is $pid"

echo "checking ps for tail"
ps -ef | grep $pid
echo "checked ps for tail"

(sleep "$interval" ; kill "$pid") &
killpid=$!

echo "counting $interval seconds"
sleep $interval

echo ""
echo "killpid is $killpid"

wait $killpid


echo ""
echo "$interval seconds have passed"

echo "killpid $killpid should be dead now"

echo ""

echo "checking ps for kill"
ps -ef | grep $killpid
echo "checked ps for kill"

echo ""

echo "tail pid $pid should be dead now"

echo "rechecking ps for tail"
ps -ef | grep $pid
echo "rechecked ps for tail"

echo ""


done

【讨论】:

以上是关于在while循环中自毁子进程(Bash)的主要内容,如果未能解决你的问题,请参考以下文章

bash常用命令

Bash脚本,while循环中的多个条件

在 Bash 的“while”循环中使用“if”

在使用读取(bash)的while循环中禁用用户输入

ssh在bash中打破while循环[重复]

ssh在bash中打破while循环[重复]