Search code examples
cprocessforkwait

What happen when a child process encounter a wait instruction?


Say I have the following code:

int main(int argc, char *argv []) {
    pid_t pid = fork();
    if (pid > 0) {
        execv(*argv, argv); 
        }
    int state=0;
    wait(&state);
    return state;
}

Does the child simply ignore the wait and skip over since it's not the calling process?


Solution

  • It will return -1 and set errno to ECHILD since the child process has no children of its own to wait on. From the wait(2) man page:

    Return value

    • wait(): on success, returns the process ID of the terminated child; on error, -1 is returned.

    • ...

    Each of these calls sets errno to an appropriate value in the case of an error.

    Errors

    • ECHILD (for wait())
      The calling process does not have any unwaited-for children.

    • ...


    Note that the logic here is backwards from the norm:

    if (pid > 0) {
        execv(*argv, argv); 
    }
    

    Here the parent process is calling execv(). Usually it's the child that does so when pid == 0, and it's the parent that waits.