在Ubuntu上重新生成挂起进程的最佳语言/方法?

时间:2011-10-05 13:26:51

标签: linux bash scripting ubuntu awk

我有一个运行多个ffmpeg实例的Ubuntu Oneiric服务器(每个实例转码一个实时视频源)。其中一个ffmpeg实例会不时挂起。通过“挂起”我的意思是这个过程没有结束,只是坐在那里什么都不做。我正在使用Upstart自动重新生成崩溃的进程,这可以正常工作,但它不会检测进程何时挂起。

在CLI中,我可以使用“ps axo pid,pcpu,comm | grep ffmpeg”轻松检测哪个进程已挂起。对于未挂起的进程,pcpu值将> 200,但对于一个挂起它,它将是100(或非常接近它)。在这种情况下,我只需要杀死挂起的进程并Upstart跳入并重新生成它。

我对Linux很新,所以我的问题是:自动化这项技术/语言的最佳方法是什么?我想我需要做的是解析ps的输出,找到pcpu接近100的实例,然后杀死那些实例。

感谢。

˚F

2 个答案:

答案 0 :(得分:1)

我不知道它是否是最好的技术/语言,但awk会起作用,例如。

$ ps axo pid,comm,pcpu | awk '/ffmpeg/ {if ($3 >= 10.0) print $1}'

将使用超过10%的CPU为您提供所有ffmpeg进程的PID。

-o

答案 1 :(得分:1)

在user980473的答案上建立我可能也会使用awk,但只是返回PID我会调用我的命令并将其传递给bash。虽然,我会删除grep并只使用awk并在大括号内移动条件语句。

ps axo pid,comm,pcpu| awk '/ffmpeg/ {if ($3 <= 15.0 && $3 >= 10.0) print "kill -9 "$1}' | bash

请注意我的条件表达式有点精致。因为user980473也会打印大于10.0的PID。看来ffmpeg的工作流程大约是20%?你不想杀掉那些。我看起来在10-15%之间,但这很容易被提炼出来。您注意到awk将打印kill -9 $ 1到stdout但是,使用管道来打击这些调用将是“热”。

我不熟悉暴发户,但你可以提供更多命令。也许您需要调用本地python脚本后,命令看起来几乎相同,但在$ 1之后你会有“; ./rebootScript.py”

ps axo pid,comm,pcpu| awk '/ffmpeg/ {if ($3 <= 15.0 && $3 >= 10.0) print "kill -9 "$"; ./rebootScript.py"}'

所以这不是问你怎么做的?坐在CLI并且每隔5分钟键入一次是不可思议的。 这是我建立一个cron工作的地方。

将此文件另存为bash脚本

#!/bin/bash

ps axo pid,comm,pcpu| awk '/ffmpeg/ {if ($3 <= 15.0 && $3 >= 10.0) print "kill -9 "$1}' | bash

NEXT,设置正确的权限。 sudo chmod +x ./ffmpegCheck.sh

并将脚本移动到您想要保留的位置。我会把我放在mv ffmpegCheck.sh /usr/local/bin/ffmpegcheck

这将允许我通过简单地调用ffmpegcheck

来调用它 root的

crontab -lsudo crontab -l将显示当前的cron文件..

它应该看起来像这样

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

您需要在列表中添加条目。我会输入sudo crontab -e,但还有其他方法。 并添加 */3 * * * * /usr/local/bin/ffmpegcheck # ffmpeg check

这将每3分钟运行一次脚本。这可以配置一些。祝你好运。