#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <signal.h>
#include <pwd.h>
#include "../lpi.h"

void handler(int signo);

int
main(int argc, char *argv[])
{
    struct passwd *pwd;
    struct sigaction sa;
    uid_t uid;

    uid = 1000;
    if (argc == 2) {
        if ((errno = toInt(argv[1], (int *) &uid)) != 0)
            err(EXIT_FAILURE, "toInt('%s')", argv[1]);
    }

    if ((pwd = getpwuid(uid)) == NULL) {        // getpwuid() is a nonreentrant
                                                // function. it returns a
                                                // statically allocated memory
        err(EXIT_FAILURE, "getpwuid");
    }

    sigemptyset(&sa.sa_mask);
    sa.sa_handler = handler;
    if (sigaction(SIGINT, &sa, NULL) == -1)
        err(EXIT_FAILURE, "sigaction");

    printf("for exit type Control-\\\n");

    for ( ; ; ) {
        printf("getpwuid(%d)=%s\n", uid, pwd->pw_name);
        sleep(3);
    }

    exit(EXIT_SUCCESS);
}

void
handler(int signo)
{
    struct passwd *pwd;
    uid_t uid;

    errno = 0;
    uid = 1;

    if ((pwd = getpwuid(uid)) == NULL) {        // refer to comment line 25
        warn("getpwuid(%d)", uid);
    }
    printf("\n");
}
