Sample parent process using wait()

The following sample illustrates the use of wait() for waiting for child processes to terminate.

 * waitchild.c
 * This is an example of a parent process that creates some child
 * processes and then waits for them to terminate. The waiting is
 * done using wait(). When a child process terminates, the
 * wait() function returns.

#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

main(int argc, char **argv)
    char                *args[] = { "child", NULL };
    int                 i, status;
    pid_t               pid;
    struct inheritance  inherit;

    // create 3 child processes
    for (i = 0; i < 3; i++) {
        inherit.flags = 0;
        if ((pid = spawn("child", 0, NULL, &inherit, args, environ)) == -1)
            perror("spawn() failed");
            printf("spawned child, pid = %d\n", pid);

    while (1) {
        if ((pid = wait(&status)) == -1) {
            perror("wait() failed (no more child processes?)");
        printf("a child terminated, pid = %d\n", pid);
        if (WIFEXITED(status)) {
            printf("child terminated normally, exit status = %d\n",
        } else if (WIFSIGNALED(status)) {
            printf("child terminated abnormally by signal = %X\n",
        } // else see documentation for wait() for more macros

The following is a simple child process to try out with the above parent.

#include <stdio.h>
#include <unistd.h>

main(int argc, char **argv)
    printf("pausing, terminate me somehow\n");

The sigwaitinfo() function will block, waiting until any signals that the caller tells it to wait for are set on the caller. If a child process terminates, then the SIGCHLD signal is set on the parent. So all the parent has to do is request that sigwaitinfo() return when SIGCHLD arrives.