繁体   English   中英

Bash脚本可以在设置的时间量后自动终止进程,还可以处理用户中断

[英]Bash script to auto-kill a process after set amount of time, but also handle user interrupt

我有一个非常简单的Bash脚本,该脚本在批处理模式下运行top达x秒,将输出保存到文件中,并在设置的时间后自动杀死top

#!/bin/bash
# Runs top under batch mode with renewal period set to $1, saves the data to file $2,  and kills the process after $3 minutes

top -b -d $1 > $2 &

PROC=$!

(sleep $3m; kill $PROC) &

事实是,我还希望能够使用这样的方法来处理脚本进程的终止(我宁愿选择kill而不是kill)

ctrl_c()
    # run if user hits control-c
    {
      echo -en "\n*** Done ***\n"
      cleanup # some cleanup function
      kill $PROC
    }

# trap keyboard interrupt (control-c)
trap ctrl_c SIGINT

while true; do read x; sleep $1; done

有更整齐的方法吗?

为什么不给top迭代次数为运行:

(( total_runtime = $3 * 60 ))
(( iterations = total_runtime / $1 ))
top -b -d $1 -n ${iterations}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM