简体   繁体   English

使用指定的运行超时从C ++执行另一个程序

[英]Executing another program from C++ with specified running timeout

I'm writing a program (A genetic algorithm implementation) which executes another program using "system" method to calculate fitness. 我正在编写一个程序(遗传算法实现),它使用“系统”方法执行另一个程序来计算适应度。 The problem is that another program sometimes hangs for unlimited amount of time. 问题是另一个程序有时会挂起无限的时间。 How can I execute a program with some time limit from C++. 如何从C ++中执行一些有时间限制的程序。

Both POSIX and c++ solutions are appreciated. POSIX和c ++解决方案都很受欢迎。 And more or less this will be run once application so solution doesn't have to be very elegant. 或多或少这将在应用程序运行后因此解决方案不一定非常优雅。

I'm running Linux CentOS distribution and am testing on Cygwin. 我正在运行Linux CentOS发行版并在Cygwin上进行测试。 For compiler I use gcc 4.1.2 with boost library. 对于编译器,我使用gcc 4.1.2和boost库。

Any help is apreciated 任何帮助都是相关的

Instead of system , execute the program with the fork / exec idiom. 而不是system ,用fork / exec惯用法执行程序。 Before the exec , set RLIMIT_CPU to a maximum value with setrlimit in the child. exec之前,将RLIMIT_CPU设置为子级中带有setrlimit的最大值。

Make sure the child does not ignore SIGXCPU (which is very unlikely). 确保孩子不会忽略SIGXCPU (这是非常不可能的)。

您可以创建一个计时器(例如使用boost计时器 ),然后尝试终止子进程...这假设你使用forkexec来启动你的所有孩子,并且你存储了每个pid。

  1. If this 'another' program is yours or you have sources under public license it's better probably to make it not a separate program but a separate thread in the main program. 如果这个“另一个”程序是您的,或者您拥有公共许可证下的源代码,那么最好使它不是一个单独的程序,而是主程序中的一个单独的程序。 In this case you can easily control it. 在这种情况下,您可以轻松控制它。

  2. If this 'another' program is yours or you have sources under public license but don't want (or can't) follow the suggestion above may be it is easier to fix the program to prevent hanging. 如果这个“另一个”程序是您的,或者您拥有公共许可证下的来源但不希望(或不能)遵循上述建议,则可能更容易修复该程序以防止挂起。

  3. Shitty method: Shitty方法:

    • do fork(), remeber PID, call exec*("my-prog", ...) 做fork(),记住PID,调用exec *(“my-prog”,...)
    • create thread in the main program with timer. 使用计时器在主程序中创建线程。
    • when time fires kill the process using kill() and PID remembered. 当time fires使用kill()和PID记住杀死进程时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM