I'm implementing a checking system in C++. It runs executables with different tests. If the solution is not correct, it can take forever for it to finish with certain hard tests. That's why I want to limit the execution time to 5 seconds.
I'm using system() function to run executables:
system("./solution");
.NET has a great WaitForExit()
method, what about native C++?. I'm also using Qt, so Qt-based solutions are welcome.
So is there a way to limit external process' execution time to 5 seconds?
Thanks
Use a QProcess
with a QTimer
so you can kill it after 5 seconds. Something like;
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();
}
Use a separate thread for doing your required work and then from another thread, issue the
pthread_cancle ()
call after some time (5 sec) to the worker thread. Make sure to register proper handler and thread's cancelability options.
For more details refer to: http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cancel.3.html
Check out Boost.Thread to allow you to make the system call in a separate thread and use the timed_join
method to restrict the running time.
Something like:
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 hardest part is to determine how to nicely terminate the thread (note that test_thread is still running).
void WaitForExit(void*)
{
Sleep(5000);
exit(0);
}
And then use it (Windows specific):
_beginthread(WaitForExit, 0, 0);
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