Alex
Alex

Reputation: 36111

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

Upvotes: 5

Views: 5374

Answers (6)

doron
doron

Reputation: 28892

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.

Upvotes: 0

ismail
ismail

Reputation: 47602

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

Upvotes: 5

MattyT
MattyT

Reputation: 6651

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

Upvotes: 2

n0rd
n0rd

Reputation: 12640

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

Upvotes: 0

Vikram.exe
Vikram.exe

Reputation: 4585

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

Upvotes: 2

VinS
VinS

Reputation: 194

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

And then use it (Windows specific):

_beginthread(WaitForExit, 0, 0);

Upvotes: 1

Related Questions