[英]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秒?
谢谢
将QProcess
与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();
}
使用单独的线程执行所需的工作,然后从另一个线程,在工作线程一段时间(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)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.