Question

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

Was it helpful?

Solution

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();
}

OTHER TIPS

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

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

And then use it (Windows specific):

_beginthread(WaitForExit, 0, 0);

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

Solution testing system on Windows should use Job objects to restrict it's access to the system and execution time (not the real time, BTW).

If you are working with Posix compliant systems (of which MacOS and Unix generally are), use fork execv and ``waitpidinstead ofsystem`.An example can be found here. The only really tricky bit now is how to get a waitpid with a timeout. Take a look here for ideas.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top