我正在编写一个程序(遗传算法实现),它使用“系统”方法执行另一个程序来计算适应度。问题是另一个程序有时会无限期地挂起。如何从 C++ 执行有时间限制的程序。
POSIX 和 c++ 解决方案都受到赞赏。或多或少这将运行一次应用程序,因此解决方案不必非常优雅。
我正在运行 Linux CentOS 发行版并在 Cygwin 上进行测试。对于编译器,我使用 gcc 4.1.2 和 boost 库。
任何帮助表示赞赏
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++.
Both POSIX and c++ solutions are appreciated. 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. For compiler I use gcc 4.1.2 with boost library.
Any help is apreciated
发布评论
评论(3)
使用
fork
/exec
习惯用法来执行程序,而不是system
。在exec
之前,使用RLIMIT_CPU设置为最大值rel="nofollow">setrlimit
在子项中。确保子进程不会忽略
SIGXCPU
(这种情况不太可能发生)。Instead of
system
, execute the program with thefork
/exec
idiom. Before theexec
, setRLIMIT_CPU
to a maximum value withsetrlimit
in the child.Make sure the child does not ignore
SIGXCPU
(which is very unlikely).您可以创建一个计时器(例如 Boost Timer )然后尝试杀死子进程...这假设您使用fork 和 exec 来启动你的所有子进程,并且你存储了每个 pid。
You could create a timer (with boost timer for example) and then try to kill the child process... this assume that you use fork and exec to launch all your child, and you stored each pid.
如果这个“另一个”程序是您的,或者您有公共许可下的源代码,那么最好不要将其作为单独的程序,而是主程序中的单独线程。在这种情况下,您可以轻松地控制它。
如果这个“另一个”程序是您的,或者您拥有公共许可下的源代码,但不想(或不能)遵循上述建议,可能更容易修复该程序以防止挂起。
糟糕的方法:
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: