void wait_for_zombie(int s)
{
    while(waitpid(-1, NULL, WNOHANG) > 0) ;
}





void echo_lines(int csock)
{
    char buf[BUF_LEN];
    int r;

    while( (r = read(csock, buf, BUF_LEN)) > 0 ) {
        (void)write(csock, buf, r);
    }
    exit(EXIT_SUCCESS);
}





void take_connections_forever(int ssock)
{
    for(;;) {
        struct sockaddr addr;
        socklen_t addr_size = sizeof(addr);
        int csock;

        
        csock = accept(ssock, &addr, &addr_size);

        
        if ( csock == -1 ) {
            perror();
        } else if ( fork() == 0 ) {
            close(ssock);
            echo_lines(csock);
        } else {
            close(csock);
        }
    }
}





int main()
{
    struct addrinfo hints, *res;
    struct sigaction sa;
    int sock;

    
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) {
        perror();
        exit(EXIT_FAILURE);
    }

    
    if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) {
        perror();
        exit(EXIT_FAILURE);
    }

    
    sa.sa_handler = wait_for_zombie;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if ( sigaction(SIGCHLD, &sa, NULL) == -1 ) {
        perror();
        exit(EXIT_FAILURE);
    }

    
    if ( bind(sock, res->ai_addr, res->ai_addrlen) != 0 ) {
        perror();
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(res);

    
    if ( listen(sock, MAX_ENQUEUED) != 0 ) {
        perror();
        exit(EXIT_FAILURE);
    }

    
    take_connections_forever(sock);
    return EXIT_SUCCESS;
}