[英]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.