[英]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
(这是非常不可能的)。
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.
在这种情况下,您可以轻松控制它。
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. 如果这个“另一个”程序是您的,或者您拥有公共许可证下的来源但不希望(或不能)遵循上述建议,则可能更容易修复该程序以防止挂起。
Shitty method: Shitty方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.