#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <unistd.h>

enum {
    listen_queue_len = 16,
    buf_len = 4096,
};

typedef void (*signalhandler_t)(int);

static void terminate(const char *msg)
{
    perror(msg);
    exit(1);
}

void set_sigactions(int signum, signalhandler_t handler)
{
    int r;

    struct sigaction act = { 0 };
    act.sa_handler = handler;
    r = sigaction(signum, &act, NULL);
    if (r == -1)
        terminate("sigaction");
}

void handler_sigchld(int s)
{
    int pid, status, save_errno;

    save_errno = errno;

    do {
        pid = waitpid(-1, &status, WNOHANG);
    } while (pid > 0);

    errno = save_errno;
}

static void process_requests(int fd)
{
    int fd2, pid, rc;
    struct sockaddr_un addr;
    socklen_t len;
    char buf[buf_len];

    while (1) {
        len = sizeof(addr);
        fd2 = accept(fd, (struct sockaddr *) &addr, &len);
        if (fd2 == -1) {
            if (errno == EINTR)
                continue;
            terminate("accept");
        }

        pid = fork();
        if (pid == 0) {
            close(fd);
            rc = read(fd2, buf, buf_len);
            write(1, buf, rc);
            close(fd2);
            exit(0);
        }
        close(fd2);
    }
}

int main()
{
    int fd, res;
    struct sockaddr_un addr;
    char *file_name;

    set_sigactions(SIGCHLD, handler_sigchld);

    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd == -1)
        terminate("socket");

    addr.sun_family = AF_UNIX;
    file_name = "socket07.t";
    strcpy(addr.sun_path, file_name);

    res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
    if (res == -1)
        terminate("bind");

    listen(fd, listen_queue_len);
    process_requests(fd);

    close(fd);

    return 0;
}
