views:

528

answers:

3

Hello!

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?

+5  A: 

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).

Brian Agnew
+1  A: 

You can either use threads, or set up an alarm(). Below is a quick example of how to set an alarm() in Linux.

http://www.aquaphoenix.com/ref/gnu_c_library/libc_301.html#SEC301

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

void 
catch_alarm (int sig){
    printf("Alarm event triggered\n");
    signal(sig, catch_alarm);
    exit(EXIT_SUCCESS);
}

int 
main(int argc, char *argv[]){

    signal (SIGALRM, catch_alarm);
    printf("set alarm\n"); 
    alarm(3);

    while(1){
        printf("hello world\n");
    }

    return 0;
}
Sweeney
+1  A: 

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.

Adam Mitz