开发者

Killing a child process if it takes too much time

开发者 https://www.devze.com 2023-03-13 10:48 出处:网络
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?

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?

0

精彩评论

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