Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: timeout base on CPU time

Tags:

linux

timeout

Is there a way to put a timeout on a program in Linux that will be enforced based on the actual time spent by the CPU executing this program, rather than by a wall clock time? It might be that the system is heavily loaded or there are lots of context switches that would make the wall clock timeout measurements not comparable. I am looking for solution in Python, C or Bash.

like image 895
Tomek Avatar asked Sep 16 '25 20:09

Tomek


1 Answers

Here's a shell script I wrote that's similar to the timeout command.

ctimeout timeout command arg ...

The command will be killed if its CPU time exceeds the timeout value (in seconds).

It uses the ulimit -t builtin command. The underlying system call, setrlimit, takes as its argument the number of seconds of CPU time, so the timeout argument should be a whole number. bash's ulimit -t rejects an argument with a decimal point. ksh accepts an argument with a decimal point, but rounds down to the nearest whole second.

Any argument with embedded whitespace should be surrounded with \' or \".

#!/bin/sh
if test $# -lt 2
then
    echo "Usage: $0 timeout command arg ..."
    exit 126
fi
ulimit -t $1 || { echo "Error: cannot set timeout $1"; exit 126; }
shift
eval "$@"
like image 106
Mark Plotnick Avatar answered Sep 18 '25 19:09

Mark Plotnick