0

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?

Jam
  • 113
  • 2
  • 7

1 Answers1

2

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);
}
dbush
  • 205,898
  • 23
  • 218
  • 273