bash 如何使用 ulimit 限制进程的运行时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19141888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:08:24  来源:igfitidea点击:

how do I limit the running time of a process using ulimit?

linuxbashulimit

提问by user2839463

I am trying to use ulimit, a feature of the bash shell, to limit the time that a program is allowed to run. For example, I tried this:

我正在尝试使用ulimitbash shell 的一个功能来限制允许程序运行的时间。例如,我试过这个:

 $   ( ulimit -t 1; ./a.out ) 

But it does not work. it lets the ./a.outprogram run until it stops (5 seconds). Anybody know how to do this? By the way, I experimented with including a -Hon the ulimitcommand line, but it just gives this error:

但它不起作用。它让./a.out程序运行直到它停止(5 秒)。有人知道怎么做吗?顺便说一句,我尝试-Hulimit命令行中包含 a ,但它只是给出了这个错误:

bash: ulimit: cpu time: cannot modify limit: Operation not permitted

Thanks.

谢谢。

回答by ThisSuitIsBlackNot

ulimitcannot limit program run time, only CPU time. If you have GNU Coreutils, you can use the timeoutcommand instead:

ulimit不能限制程序运行时间,只能限制 CPU 时间。如果您有GNU Coreutils,则可以改用timeout命令:

timeout 1s ./a.out

This will killyour program after one second. You can specify the signal to send using -sor --signal, e.g.

这将kill在一秒钟后你的程序。您可以使用-s或指定要发送的信号--signal,例如

timeout --signal=HUP 1s ./a.out