如果我有一個內部有無限回圈的 C 代碼,我想要一個在特定時間后終止執行的命令。所以我想出了這樣的東西——
g -std=c 20 -DLOCAL_PROJECT solution.cpp -o solution.exe & solution.exe & timeout /t 0 & taskkill /im solution.exe /f
但問題在于它會首先執行程式,因此由于無限回圈,它甚至不會超時和任務終止部分。
有沒有人有任何解決方案或其他替代方案而不是超時?
我使用的是 Windows 10,我的編譯器是 gnu 11.2.0
另外,如果沒有 TLE,我不希望 taskkill 顯示此錯誤
ERROR: The process "solution.exe" not found.
uj5u.com熱心網友回復:
您的主回圈可以在某個時間限制后退出,如果您確信它被足夠定期地呼叫。
#include <chrono>
using namespace std::chrono_literals;
using Clock = std::chrono::system_clock;
int main()
{
auto timeLimit = Clock::now() 1s;
while (Clock::now() < timeLimit) {
//...
}
}
或者,您可以在主執行緒中啟動一個執行緒,在一定延遲后拋出例外:
#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();
//...
}
拋出“TimeOutException”實體后呼叫終止
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/339984.html
