shell - 如何杀死过时的进程

标签 shell ffmpeg kill pid

我在 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/

相关文章:

FFMpeg 在 Windows 下找不到 libvorbis

java - Spring - 如何杀死无限循环

c - 是什么杀死了父进程?

linux - Bash 从 TSV 文件中提取特定列到新文件,并添加带有提取列标题的额外列

linux - 在 linux bash 中用另一个命令预先挂起所有命令

从 Shell 脚本收集返回值

shell - 如何添加一个变量来计算脚本被调用的次数?

ffmpeg - 使用 ffmpeg mask 动态 Logo

javascript - Concat 音频文件然后调用创建文件

linux - 如何终止运行超过 36 小时且命令中包含特定短语的特定进程?