我在Ubuntu服务器上运行转码,有时进程过时并没有输出,但ps aux
显示进程仍在运行 - 但CPU使用率过高
我可以使用以下命令获取CPU使用率(我正在使用的ffmpeg进程具有进程ID 4416:
ps aux | grep -v grep | grep 4416 | awk '{print $3}'
我可能会创建一个小脚来杀死一个特定的进程但是如何创建一个循环来检查每个ffmpeg进程并在其失效时将其终止(runit会在之后重新启动它)?
我认为需要执行命令以使用一分钟cron获取两次CPU使用率,并在CPU使用率相同时终止该进程。我会这样做吗?
答案 0 :(得分:2)
好的,我们会做几个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"*