Waitpid equivalent with timeout?

前端 未结 10 1329
小鲜肉
小鲜肉 2020-11-27 12:10

Imagine I have a process that starts several child processes. The parent needs to know when a child exits.

I can use waitpid, but then if/when the paren

10条回答
  •  孤街浪徒
    2020-11-27 12:57

    Fork an intermediate child, which forks the real child and a timeout process and waits for all (both) of its children. When one exits, it'll kill the other one and exit.

    pid_t intermediate_pid = fork();
    if (intermediate_pid == 0) {
        pid_t worker_pid = fork();
        if (worker_pid == 0) {
            do_work();
            _exit(0);
        }
    
        pid_t timeout_pid = fork();
        if (timeout_pid == 0) {
            sleep(timeout_time);
            _exit(0);
        }
    
        pid_t exited_pid = wait(NULL);
        if (exited_pid == worker_pid) {
            kill(timeout_pid, SIGKILL);
        } else {
            kill(worker_pid, SIGKILL); // Or something less violent if you prefer
        }
        wait(NULL); // Collect the other process
        _exit(0); // Or some more informative status
    }
    waitpid(intermediate_pid, 0, 0);
    

    Surprisingly simple :)

    You can even leave out the intermediate child if you're sure no other module in the program is spwaning child processes of its own.

提交回复
热议问题