我正在用 C++ 实现一个检查系统。它运行具有不同测试的可执行文件。如果解决方案不正确,则可能需要很长时间才能完成某些严格的测试。这就是为什么我想将执行时间限制为 5 秒。
我正在使用 system() 函数来运行可执行文件:
system("./solution");
.NET 有一个很棒的WaitForExit()
方法,那么原生 C++ 呢?我也在使用 Qt,因此欢迎使用基于 Qt 的解决方案。
那么有没有办法将外部进程的执行时间限制为 5 秒?
谢谢
我正在用 C++ 实现一个检查系统。它运行具有不同测试的可执行文件。如果解决方案不正确,则可能需要很长时间才能完成某些严格的测试。这就是为什么我想将执行时间限制为 5 秒。
我正在使用 system() 函数来运行可执行文件:
system("./solution");
.NET 有一个很棒的WaitForExit()
方法,那么原生 C++ 呢?我也在使用 Qt,因此欢迎使用基于 Qt 的解决方案。
那么有没有办法将外部进程的执行时间限制为 5 秒?
谢谢
aQProcess
和 a 一起使用,QTimer
这样你就可以在 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();
}
使用单独的线程来完成所需的工作,然后从另一个线程,
pthread_cancle ()
在一段时间(5 秒)后向工作线程发出调用。确保注册正确的处理程序和线程的可取消性选项。
有关详细信息,请参阅:http ://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cancel.3.html
查看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 仍在运行)。
void WaitForExit(void*)
{
Sleep(5000);
exit(0);
}
然后使用它(特定于 Windows):
_beginthread(WaitForExit, 0, 0);
Windows 上的解决方案测试系统应该使用Job 对象来限制它对系统的访问和执行时间(不是实时,顺便说一句)。