限制程序在Linux中运行的时间 [英] Limiting the time a program runs in Linux

查看:213
本文介绍了限制程序在Linux中运行的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux中,我只想运行一个程序,但只能运行有限的时间,例如1秒.如果程序超出此运行时间,我想终止该进程并显示错误消息.

In Linux I would like to run a program but only for a limited time, like 1 second. If the program exceeds this running time I would like to kill the process and show an error message.

推荐答案

StackOverflow不允许我删除答案,因为它是可接受的答案.由于它在列表顶部,下面有一个更好的解决方案,因此它获得了否决票.如果您使用的是GNU系统,请按照@wRAR的建议使用timeout.因此,希望您停止投票,这是它的工作方式:

StackOverflow won't allow me to delete my answer since it's the accepted one. It's garnering down-votes since it's at the top of the list with a better solution below it. If you're on a GNU system, please use timeout instead as suggested by @wRAR. So in the hopes that you'll stop down-voting, here's how it works:

timeout 1s ./myProgram 

您可以将smhd用作秒(默认值,如果省略),分钟,小时或天.一个很有趣的功能是,您可以指定另一个选项-k 30s(在上述1s之前),以便在30秒后如果不响应原始SIGTERM,则用SIGKILL杀死它.

You can use s, m, h or d for seconds (the default if omitted), minutes, hours or days. A nifty feature here is that you may specify another option -k 30s (before the 1s above) in order to kill it with a SIGKILL after another 30 seconds, should it not respond to the original SIGTERM.

一个非常有用的工具.现在向下滚动并向上投票@wRAR的答案.

A very useful tool. Now scroll down and up-vote @wRAR's answer.

为了后代,这是我最初的(次等的)建议,可能仍然是某人有用.

For posterity, this was my original - inferior - suggestion, it might still be if some use for someone.

一个简单的bash脚本应该可以为您完成

A simple bash-script should be able to do that for you

./myProgram &
sleep 1
kill $! 2>/dev/null && echo "myProgram didn't finish"

应该这样做.

$!扩展到最后一个后台进程(通过使用&),并且kill如果没有杀死任何进程,则kill返回false,因此仅在实际上杀死了某些东西的情况下才执行echo.

$! expands to the last backgrounded process (through the use of &), and kill returns false if it didn't kill any process, so the echo is only executed if it actually killed something.

2>/dev/null重定向kill的stderr,否则它将打印出一些内容,告诉您它无法终止该进程.

2>/dev/null redirects kill's stderr, otherwise it would print something telling you it was unable to kill the process.

您可能还想添加-KILL或您想用来摆脱进程的任何信号.

You might want to add a -KILL or whichever signal you want to use to get rid of your process too.

编辑
正如ephemient指出的那样,如果您的程序完成了,而其他进程抢走了pid,它就会被杀死,这是一场竞赛.为了降低发生这种情况的可能性,您可以对SIGCHLD做出反应,而不要尝试杀死它.仍然有机会杀死错误的进程,但是它非常遥远.

EDIT
As ephemient pointed out, there's a race here if your program finishes and the some other process snatches the pid, it'll get killed instead. To reduce the probability of it happening, you could react to the SIGCHLD and not try to kill it if that happens. There's still chance to kill the wrong process, but it's very remote.

trapped=""
trap 'trapped=yes' SIGCHLD
./myProgram &
sleep 1
[ -z "$trapped" ] && kill $! 2>/dev/null && echo '...'

这篇关于限制程序在Linux中运行的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆