How does parent process get the termination status through wait from a child process which calls _exit

前端 未结 4 432
滥情空心
滥情空心 2021-01-15 16:31

I have read the following statement.

The status argument given to _exit() defines the termination status of the process, which is available to the p

4条回答
  •  孤城傲影
    2021-01-15 16:59

    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.

提交回复
热议问题