Killing a child process if it takes too much time
When using the fork
system call in C++, what is the easiest way to kill a child process if it takes too much time to execute what it is supposed to execute?
Like if somehow it gets into an infinite loop.. What should the parent process do to set the timeout for 开发者_Python百科the child process?
Use WNOHANG
with waitpid
and sleep in between. Something like this should do it:
while (times < max_times) {
sleep(5); /* sleep 5 seconds */
rc = waitpid(-1, &status, WNOHANG);
if (rc < 0) {
perror("waitpid");
exit(1);
}
if (WIFEXITED(status) || WIFSIGNALED(status)) {
/* it's done */
break;
}
times++;
}
if (times == max_times) {
/* ... */
}
I think you need waitpid
with timeout and on timeout kill
child process (assuming that child is hung). Check this page for ideas:
Waitpid equivalent with timeout?
精彩评论