#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <err.h>

void handler(int sig);
int siginterrupt1(int sig, int flag);

int
main(int argc, char *argv[])
{
    struct sigaction sa;
    int n, sig;
    char buf[BUFSIZ];

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = handler;

    sig = SIGINT;
    if (sigaction(sig, &sa, NULL) == -1)
        err(EXIT_FAILURE, "sigaction");

    if (argc == 2)
        if (strcmp(argv[1], "norestart") == 0)
            if (siginterrupt1(sig, 1) == -1)
                err(EXIT_FAILURE, "siginterrupt1");

    printf("PID=%ld\n", (long) getpid());
    if ((n = read(STDIN_FILENO, buf, BUFSIZ)) == -1)
        err(EXIT_FAILURE, "read");

    if (n == 0)
        printf("EOF\n");
    else {
        buf[n] = '\0';
        printf(">> %s", buf);
    }

    exit(EXIT_SUCCESS);
}

int
siginterrupt1(int sig, int flag)
{
    struct sigaction sa;

    if (sigaction(sig, NULL, &sa) == -1)
        return -1;

    if (flag)
        sa.sa_flags &= ~SA_RESTART;
    else
        sa.sa_flags |= SA_RESTART;

    if (sigaction(sig, &sa, NULL) == -1)
        return -1;

    return 0;
}

void
handler(int sig)
{
    printf("caught signal %d (%s)\n", sig, strsignal(sig));
}
