12

If I use wait(null), and I know (for sure) that the child will finish (exit) before we reach to wait(null) in the parent process, does the wait(null) block the parent process?

I mean, the wait() won't get any signal, right?

int main() {
    int pipe_descs[2];
    int i, n, p;

    srand(time(NULL(;
    pipe(pipe_descs);

    for (i = 0; i < 2; i++) {
        pid_t status = fork();

        if (status == 0) {
            n = rand() % 100;
            p = (int) getpid();

            write(pipe_descs[1], &n, sizeof(int));
            write(pipe_descs[1], &p, sizeof(int));
            exit(0);
        }
        else {
            read(pipe_descs[0],  &n,  sizeof(int));
            read(pipe_descs[0],  &p,  sizeof(int));
            printf(" %d %d\n", n, p);
            wait(NULL); // (1)
        }
    }
    return 0;
}
3
  • 8
    Perhaps read the man page: "If a child has already changed state, then these calls return immediately". or perhaps just run it under those conditions and see what happens?
    – kaylum
    Feb 23, 2017 at 21:51
  • In any case I can't think of any way to be certain that the child has terminated before the parent wait()s for it, except for the parent to handle SIGCHLD manually. In particular, it is not safe to assume that that will always happen in your example code. Feb 23, 2017 at 21:58
  • 1
    What is null? Feb 23, 2017 at 22:12

1 Answer 1

31

wait(NULL) will block the parent process until any of its children has finished. If the child terminates before the parent process reaches wait(NULL) then the child process turns to a zombie process until its parent waits on it and its released from memory.

If the parent process doesn't wait for its child, and the parent finishes first, then the child process becomes an orphan and is assigned to init as its child. And init will wait and release the process entry in the process table.

In other words: the parent process will be blocked until the child process returns an exit status to the operating system which is then returned to the parent process. If the child finishes before the parent reaches wait(NULL) then it will read the exit status, release the process entry in the process table and continue execution until it finishes as well.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.