Home > Mobile >  command to kill/stop the program if it runs more than a certain time limit
command to kill/stop the program if it runs more than a certain time limit

Time:10-29

If I have a C code with an infinite loop inside i want a command that will kill the execution after certain time. so i came up with something like this-

g -std=c 20 -DLOCAL_PROJECT solution.cpp -o solution.exe & solution.exe & timeout /t 0 & taskkill /im solution.exe /f

But the problem with this was that it would first execute the program so due to the infinite loop it won't even come to timeout and taskkill part.

Does anybody have any solution to it or other alternatives instead of timeout?

I am using windows 10 and my compiler is gnu 11.2.0

Also in case there is No TLE i don't want taskkill to show this error

ERROR: The process "solution.exe" not found.

CodePudding user response:

Your main loop could exit after a certain time limit, if you're confident it is called regularly enough.

#include <chrono>

using namespace std::chrono_literals;
using Clock = std::chrono::system_clock;

int main()
{
    auto timeLimit = Clock::now()   1s;
    while (Clock::now() < timeLimit) {
        //...
    }
}

Alternatively you could launch a thread in your main throwing an exception after a certain delay:

#include <chrono>
#include <thread>

using namespace std::chrono_literals;
struct TimeOutException {};

int main()
{
    std::thread([]{
        std::this_thread::sleep_for(1s); 
        std::cerr << "TLE" << std::endl;
        throw TimeOutException{};
    }).detach();

    //...
}

terminate called after throwing an instance of 'TimeOutException'

  • Related