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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With