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

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

【问题讨论】:

    标签: bash while-loop timeout sleep kill


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2014-05-27
      • 2020-07-29
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多