How to exit a process with C ++ if it takes more than 5 seconds?

I am implementing a C ++ validation system. It runs executable files with various tests. If the solution is not correct, it may require endless completion with certain stringent tests. So I want to limit the runtime to 5 seconds.

I use the system () function to run executable files:

system("./solution"); 

.NET has an excellent WaitForExit() method, but what about native C ++ ?. I also use Qt, so Qt based solutions are welcome.

So, is there a way to limit the runtime of an external process to 5 seconds?

thanks

+4
source share
6 answers

Use QProcess with QTimer so you can kill it after 5 seconds. Sort of:

 QProcess proc; QTimer timer; connect(&timer, SIGNAL(timeout()), this, SLOT(checkProcess()); proc.start("/full/path/to/solution"); timer.start(5*1000); 

and implement checkProcess() ;

 void checkProcess() { if (proc.state() != QProcess::NotRunning()) proc.kill(); } 
+5
source

Use a separate thread to do the required work, and then from another thread, make a pthread_cancle () call after a while (5 seconds) into the work thread. Be sure to register the correct options for canceling the handler and thread.

See http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cancel.3.html for more details.

+2
source
 void WaitForExit(void*) { Sleep(5000); exit(0); } 

And then use it (for Windows):

 _beginthread(WaitForExit, 0, 0); 
+1
source

Check Boost.Thread so that you can make a system call in a separate thread and use the timed_join method to limit the running time.

Sort of:

 void run_tests() { system("./solution"); } int main() { boost::thread test_thread(&run_tests); if (test_thread.timed_join(boost::posix_time::seconds(5))) { // Thread finished within 5 seconds, all fine. } else { // Wasn't complete within 5 seconds, need to stop the thread } } 

The most difficult task is to determine how to nicely terminate the thread (note that test_thread still works).

+1
source

The Windows Solution Testing System should use Job Objects to limit access to the system and runtime (not real-time, BTW).

0
source

If you work with Posix-compatible systems (of which MacOS and Unix are usually), use fork execv and `waitpid instead of system`. An example can be found here . The only really difficult bit now is how to get a waitpid with a timeout. Take a look here for ideas.

0
source

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


All Articles