简体   繁体   中英

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 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM