Skip to content
Advertisement

How to kill a process after a given real running time in Bash?

For killing a process after a given timeout in Bash, there is a nice command called timeout. However, I’m running my program on a multi-user server, and I don’t want the performance of my program to be influenced by others. Is there a way to kill a process in Bash, after a given time that the program is really running?

Advertisement

Answer

On Bash+Linux, you can use ulimit -t. Here’s from help ulimit:

 -t        the maximum amount of cpu time in seconds

Here’s an example:

$ time bash -c 'ulimit -t 5; while true; do true; done'
Killed

real    0m8.549s
user    0m4.983s
sys     0m0.008s

The infinite loop process was scheduled (i.e. actually ran) for a total of 5 seconds before it was killed. Due to other processes competing for the CPU at the same time, this took 8.5 seconds of wall time.

A command like sleep 3600 would never be killed, since it doesn’t use any CPU time.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement