开发者

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++.

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 开发者_JAVA百科4.1.2 with boost library.

Any help is apreciated


Instead of system, execute the program with the fork/exec idiom. Before the exec, set RLIMIT_CPU to a maximum value with setrlimit in the child.

Make sure the child does not ignore SIGXCPU (which is very unlikely).


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.


  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:

    • do fork(), remeber PID, call exec*("my-prog", ...)
    • create thread in the main program with timer.
    • when time fires kill the process using kill() and PID remembered.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜