我在 Ubuntu 服务器上运行转码,有时该过程过时并且不提供输出,但 ps aux
显示进程仍在运行 - 但 CPU 使用率过时
我可以使用以下命令获取 CPU 使用率(我正在使用的 ffmpeg 进程的进程 ID 为 4416:
ps aux | grep -v grep | grep 4416 | awk '{print $3}'
我可能会创建一个小脚本来杀死一个特定的进程,但是我将如何创建一个循环来检查每个 ffmpeg 进程并在它过时时杀死它(runit 将在之后重新启动它)?
我认为它需要执行命令以用一分钟的 cron 两次获取 CPU 使用率,如果 CPU 使用率相同,则终止该进程。我会这样做吗?
最佳答案
好的,所以我们做一对ps aux
请求,然后我们将检查陈旧的进程。
#!/bin/bash
# setup, change this if undesired
workdir="/tmp/.stale_process_killing"
[ -d "$workdir" ] || mkdir "$workdir"
# get ps aux outputs, change number of iterations if desired
for ((i=1; i<5; i++)); do
# add file number to file
echo $i > "${workdir}/psaux${i}"
# add ps output to file
ps aux | grep 'ffmpeg' >> "${workdir}/psaux${i}"
# change this timeout to suit your needs
sleep 1
done
# now parse the files using awk
awk '
FNR==1 { ix = $1 }
FNR!=1 { cpu[$2][ix] = $3 }
END {
for (pid in cpu) {
j=1;
while (cpu[pid][j] == cpu[pid][j+1] && j <= ix) {
if (cpu[pid][j++] == "") {
j=1;
break;
}
}
if (j >= ix) {
system("kill " pid);
}
}
}' "${workdir}/psaux"*
包含调试打印的版本,以安全检查。
#!/bin/bash
# setup, change this if undesired
workdir="/tmp/.stale_process_killing"
[ -d "$workdir" ] || mkdir "$workdir"
# get ps aux outputs, change number of iterations if desired
for ((i=1; i<5; i++)); do
# add file number to file
echo $i > "${workdir}/psaux${i}"
# add ps output to file
ps aux | grep 'ffmpeg' >> "${workdir}/psaux${i}"
# change this timeout to suit your needs
sleep 1
done
# now parse the files using awk
awk '
FNR==1 { ix = $1 }
FNR!=1 { cpu[$2][ix] = $3 }
END {
for (pid in cpu) {
j=1;
while (cpu[pid][j] == cpu[pid][j+1] && j <= ix) {
print cpu[pid][j]
if (cpu[pid][j++] == "") {
j=1;
break;
}
}
if (j >= ix) {
print "kill " pid;
} else {
print "no kill " pid;
}
}
}' "${workdir}/psaux"*
关于shell - 如何杀死过时的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585427/