Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 622
Alex Avatar asked Jan 01 '11 10:01

Alex


4 Answers

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();
}
like image 91
ismail Avatar answered Oct 28 '22 11:10

ismail


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

like image 2
Vikram.exe Avatar answered Oct 28 '22 10:10

Vikram.exe


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

like image 2
MattyT Avatar answered Oct 28 '22 11:10

MattyT


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

And then use it (Windows specific):

_beginthread(WaitForExit, 0, 0);
like image 1
VinS Avatar answered Oct 28 '22 11:10

VinS