Wednesday, November 28, 2007

Limiting the runtime of a program

I have some programs that run in a cron job at night and occasionally they hang and don't exit which means that anything scheduled after them doesn't run and the next day I have processes hanging around. To solve that I made a twelve line program that uses features in QProcess to automatically kill a process that is taking longer then five minutes. Here is the slightly bigger version that lets you specify the timeout if you want and has a help.
timelimit -l 60000 ./reallyLongrunningapp

#include QtCore
int main(int argc, char **argv)
if (argc < 2) {
QTextStream out(stderr);
out << "Usage: timelimit -l 1000 command [args]" << endl;
return -1;

QProcess process;
QStringList arguments;
for (int i = 2; i < argc; ++i)
QString command = argv[1];
int timeLimit = 1000 * 60 * 5;
if (argc > 3 && command == "-l") {
bool ok;
int userLimit = arguments.value(0).toInt(&ok);
if (ok) {
timeLimit = userLimit;
command = argv[3];
process.start(command, arguments);
return process.exitCode();


Pavel said...

The standard 'timeout' program also does this, killing a process with a specified signal. I've used it in my cron jobs ever since running into the problem you describe forced me to discover it. :)


Niels Aan de Brugh said...

You don't need a new program and Qt for that, Bash (as well as most shells I guess) have the option to limit a user process in more than one way.

man bash
Look for 'ulimit', specifically the -t option. Note that this limits the time the process is actually on the CPU.

Johannes said...

sleep $(read -p "how long to wait: "; echo $REPLY)
[[ $(jobs -p) =~ $! ]] && kill $!

Popular Posts