Search code examples
cforkwaitpid

For waitpid, how do I know if the child finishes its process?


First, I fork a child to do something, and I use waitpid(-1, &child_status, WNOHANG); in the parent to let parent continue instead of waiting for child to finish.

How do I know when the child finished its process?


Solution

  • You can set up a signal handler for SIGCHLD which gets sent automatically when a child process exits.

    The signal processor can then set a global flag which can be periodically checked in other parts of the program. If the flag is set, call wait or waitpid to get the child's exit status.

    int child_exit_flag = 0;
    
    void child_exit(int sig)
    {
        child_exit_flag = 1;
    }
    
    ...
    
    signal(SIGCHLD, child_exit);
    
    ...
    
    if (child_exit_flag) {
        pid_t pid;
        int status;
    
        child_exit_flag = 0;
        pid = wait(&status);
        printf("child pid %d exited with status %d\n", pid, status);
    }