How does the parent process get termination status by waiting for a child process that calls _exit

advertisements

I have read the following statement.

The status argument given to _exit() defines the termination status of the process, which is available to the parent of this process when it calls wait().

A process is always successfully terminated by _exit() (i.e., _exit() never returns).

Question

If _exit doesn't return, how does the parent process can get the termination status from the child process through the wait?


Whenever a process exits (whether or not by calling _exit(int Exit_Status) ) the kernel sends SIGCHLD function to its parent. the parent may either

     1. Ignore the incoming signal
     2. Catch it by installing a signal handler

Specifically the parent may catch the exit status by calling the wait()or waitpid() function. In this case the LSB is made available to the parent. Specifically the status may be learnt as follows

    int status;
    wpid = waitpid(child_pid, &status, WUNTRACED);

Since only the last 8 bits are available it will be logical to mask the upper bit by doing a bitwise and operation with 255. A system defined macro does this for you

   WEXITSTATUS(status);

Thus in order to get the child status - you may use after the waitpid statement

   printf("child exited, status=%d\n", WEXITSTATUS(status));

Ignoring the SIGCHLD may lead to creation of zombie (defunct) process(es). Setting SA_NOCLDWAIT flag for SIGCHLD does not produce a zombie as the kernel reaps them. However, the code is not portable and its better to use wait system call.