shell脚本:如何将进程运行时间与阈值进行比较?
Bash 脚本应该检查某个进程的运行时间是否超过一定的分钟数,如果超过则终止它。
我可以通过类似 That Gives 9:47.31
的方式来获取运行时间
ps -aux | grep ProgramName | grep -v grep | awk '{print $10}'
例如, 。但我应该在哪里进一步检查该值是否大于(例如 10 分钟)阈值?
Bash script should check if a certain process is running more than a certain number of minutes, and kill it if does.
I can get the running time by something like
ps -aux | grep ProgramName | grep -v grep | awk '{print $10}'
That gives 9:47.31
for instance. But where do I go further and check if that is greater than, say 10 minutes threshold?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下是您的用例所需的 awk 1 衬垫:
另请注意,
ps -o etime -C ProgramName
为您提供自 ProgramName 运行以来的时间,因此您无需使用您的这次获取的命令过于复杂。重要提示:另请记住,对于运行超过一天的进程,您将获得
ps
命令的输出,如1-21:48 所示: 48.
.我的 awk 命令中没有涵盖这种情况,但您可以使用与上面所示相同的awk split
命令。更新:根据下面的评论,请将此版本用于 FreeBSD 或任何其他风格的 Unix(例如:Mac),其中
-C ProgramName
选项不可用。Here is the awk 1 liner you'll need for your use case:
Also note that
ps -o etime -C ProgramName
gives you the time since ProgramName has been running so you don't need to use your overly complicated command to get this time.IMPORTANT: Also remember that for the processes that have been running for more than a day you will get output of
ps
command as something like1-21:48:48
. I don't have this case covered in my awk command but you can use the sameawk's split
command as I have shown above.UPDATE: As per the comment below, use this version for FreeBSD or any other flavor of Unix (eg: Mac) where
-C ProgramName
option is not available.这是一种可能的方法:
顺便说一句,您不需要 gerp -v grep,您可以这样做:
也就是说,我很想看到其他解决方案,因为我觉得我正在回收这种方法......
Here is one possible way:
BTW, you don't need to gerp -v grep, you can do:
That said, I'd love to see other solution, because I feel I'm recycling this methods...
首先,您可以使用以下命令来避免不必要的 grep -v grep 和 awk dance:
在我的 Linux 机器上,这似乎以 HH:MM:SS 格式给出时间。
考虑到 pidof ProgName 可能会给出多个值,您可以使用 tail -n +2|head -1 或类似的东西来处理它。
现在要获取持续时间,您可以将时间转换为秒:
请注意,
ps -o time
给出的时间也可能采用以下格式:D-HH:MM:SS
> 其中 D 是天数。First, you can avoid the unnecessary grep -v grep and awk dance with the following instead:
On my linux machine this seems to give the time in the format HH:MM:SS.
Taking into consideration that
pidof ProgName
might give more than one value you might handle that withtail -n +2|head -1
or something like that.Now to get the duration you can convert the time into seconds:
Note that the time given by
ps -o time
might be in this format too:D-HH:MM:SS
where D is the number of days.这适用于程序运行时间少于一天的情况
如果您想要更高的阈值,您将需要在提取进程时间方面添加更多逻辑,但那时我会将内容放入 perl/ruby 中脚本并通过
`ps auxww
w` 获取信息This will work for cases where your program has run less than a day
If you want higher thresholds, you'll want to put some more logic around the extraction of process time, but at that point I'd put things into a perl/ruby script and get the information via
`ps auxww
w`