Skip to main content
 首页 » 编程设计

linux之Bash 脚本在设定的时间后自动终止进程,还处理用户中断

2026年05月17日24cloudgamer

我有一个非常简单的 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 )

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}