簡體   English   中英

如果超過5秒,如何使用C ++退出進程?

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

我正在用C ++實現一個檢查系統。 它使用不同的測試運行可執行文件。 如果解決方案不正確,可能需要永遠完成某些硬測試。 這就是為什么我想將執行時間限制為5秒。

我正在使用system()函數來運行可執行文件:

system("./solution");

.NET有一個很好的WaitForExit()方法,那么本機C ++呢? 我也使用Qt,因此歡迎基於Qt的解決方案。

那么有沒有辦法將外部進程的執行時間限制為5秒?

謝謝

QProcessQTimer配合使用,以便在5秒后將其殺死。 就像是;

QProcess proc;
QTimer timer;

connect(&timer, SIGNAL(timeout()), this, SLOT(checkProcess());
proc.start("/full/path/to/solution");
timer.start(5*1000);

並實現checkProcess() ;

void checkProcess()
{
    if (proc.state() != QProcess::NotRunning())
        proc.kill();
}

使用單獨的線程執行所需的工作,然后從另一個線程,在工作線程一段時間(5秒)后發出pthread_cancle ()調用。 確保注冊正確的處理程序和線程的可取消性選項。

有關更多詳細信息,請訪問: http//www.kernel.org/doc/man-pages/online/pages/man3/pthread_cancel.3.html

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

然后使用它(Windows特定):

_beginthread(WaitForExit, 0, 0);

檢查Boost.Thread以允許您在單獨的線程中進行系統調用,並使用timed_join方法來限制運行時間。

就像是:

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
    }
}

最難的部分是確定如何很好地終止線程(注意test_thread仍在運行)。

Windows上的解決方案測試系統應該使用Job對象來限制它對系統和執行時間的訪問(而不是實時,BTW)。

如果你正在使用Posix兼容系統(通常是MacOS和Unix),請使用fork execv和``waitpid instead of system`。可以在這里找到一個例子。 現在唯一真正棘手的一點是如何獲得一個超時的waitpid。 看看這里的想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM