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

void sig_handler(int signo);

int
main(int argc, char *argv[])
{
    int fds[2];
    long chld_pid;
    int status;
    int pid;

    signal(SIGPIPE, sig_handler);
    signal(SIGCHLD, sig_handler);

    if (pipe(fds) == -1)
        err(EXIT_FAILURE, "pipe");

    if ((pid = fork()) == -1)
        err(EXIT_FAILURE, "fork");

    if (pid == 0) {
        exit(100);              /* exit as soon as possible */
    }

    sleep(2);                   /* make sure child terminates first */
    close(fds[0]);              /* close read end of pipe */
    write(fds[1], "123\n", 4);
    chld_pid = wait(&status);

    printf("child with PID=%ld exit with status=%d\n",
            (long) chld_pid, WEXITSTATUS(status));
    exit(EXIT_SUCCESS);
}

void
sig_handler(int signo)
{
    if (signo == SIGPIPE)
        printf("SIGPIPE caught\n");
    else if (signo == SIGCHLD)
        printf("SIGCHLD received from a child\n");
}
