我有一个非常简单的 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}
关于linux - Bash 脚本在设定的时间后自动终止进程,还处理用户中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20152810/