简体   繁体   中英

How is wait implemented in C?

When I create two child processes, I can't use SIGCHLD to tell whether both child processes have terminated since once a signal is delivered, future signals of the same type are discarded. When I receive a SIGCHLD signal and handle that signal, I cannot be sure whether that means both child processes have terminated and sent the SIGCHLD signal or just one of them has terminated. In other words, signals are not queued. However, with the function wait(), if I have two child processes, then I can call wait() twice to reap both child processes, and I wonder how it is implemented under the hood. It seems it is not using SIGCHLD as signals are not queued. So how is it able to handle terminated child processes one by one?

In cases like this, you'd instead call waitpid() with the WNOHANG flag in a loop until it returns 0 to indicate none of the specified processes have changed state (or -1 to indicate an error).

int status;
pid_t p;
while ((p = waitpid(-1, &status, WNOHANG)) > 0) {
    // Inspect status and do whatever
}

As for how they work under the hood? The kernel keeps exited but not yet waited for processes in its list of processes (so called zombie processes). wait() just returns the status of one of the caller's exited children, or blocks until there is one (or an error), at which point the calling process is scheduled to run again.

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