Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout for a program?

I'm currently trying to make a small testing application for various programming tasks. It will run executable file which will generate output on another file and then compare it with answer. This far I think I will be able to get easy, but I have a problem...

I want to limit the time that this executable file can run, for example, 1 second or 2 seconds. So I was wondering is there an option which halts/exits the program if time limit is reached.

Operating system for now isn't a problem it can be windows or linux, though I would later switch the program to linux anyways, so it would be better if someone could give me some hint on how to do this.

So enough of 'blabbering' and I will just ask the question: Is there a way to set time limit for how long program can run either on Linux or Windows?

like image 784
enoyhs Avatar asked Dec 29 '22 21:12

enoyhs


2 Answers

This script looks like it will do the job for Linux (excerpt below).

cleanup()
{
    kill %1 2>/dev/null             #kill sleep $timeout if running
    kill %2 2>/dev/null && exit 128 #kill monitored job if running
}

set -m               #enable job control
trap "cleanup" CHLD  #cleanup after timeout or command
timeout=$1 && shift  #first param is timeout in seconds
sleep $timeout&      #start the timeout
"$@"                 #start the job

It sets a sleep command running for your timeout, then executes the given program. When the sleep exits, the script will cleanup and exit (thus taking down your spawned process).

like image 126
Brian Agnew Avatar answered Jan 01 '23 12:01

Brian Agnew


In Windows, Job objects can limit for how long their contained process run. Here's an example from an open source project: sandbox.cpp See the help message at the bottom of the file for usage info.

like image 35
Adam Mitz Avatar answered Jan 01 '23 10:01

Adam Mitz