How to set a timeout for a program?

I am currently trying to create a small test application for various programming tasks. It will run an executable file that will generate output in another file, and then compare it with the answer. At the moment, I think I can easily, but I have a problem ...

I want to limit the execution time of this executable file, for example, 1 second or 2 seconds. Therefore, I was wondering if there is an option that stops / issues the program if the time limit is reached.

Currently, the operating system is not a problem, it can be windows or Linux, although I still switch the program to linux later, so it would be better if someone could give me some hint on how to do this.

โ€œChatterโ€ is enough, and Iโ€™ll just ask the question: Is there a way to set a time limit on how long a program can run on Linux or Windows?

+4
source share
3 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 the wait command to execute for your timeout, then executes the given program. When sleep comes out, the script will clear and exit (thus removing your vicious process).

+6
source

On Windows, Job objects can limit the execution time of their contained process. Here is an example from an open source project: sandbox.cpp See the Help message at the bottom of the file for usage information.

+3
source

You can use streams or set an alarm (). The following is a brief example of how to set an alarm () on 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; } 
+1
source

Source: https://habr.com/ru/post/1286517/


All Articles