#include <signal.h>
#include <stdio.h>

/* Note: this example is a modification of Program 10.11 from Stevens
 * "Advanced Unix Programming.  
 */

/* To send SIGQUIT, run "kill -QUIT <pid>".  You need to find out the pid
 * somehow, either using ps, or running the process in the background (which
 * prints to the screen the process's pid.
 */

void
sig_quit(int signo)
{

    struct sigaction newact;
    newact.sa_flags = 0;
    sigemptyset(&newact.sa_mask);
    newact.sa_handler= SIG_DFL;

    printf("caught SIGQUIT\n");

    if(sigaction(SIGQUIT, &newact, NULL) == -1)
	perror("Could not install handler for SIGQUIT");

    return;
}

int
main(void)
{
    sigset_t newmask, oldmask, pendmask;
    struct sigaction newact;

    sigemptyset(&newact.sa_mask);
    newact.sa_handler= sig_quit;
    newact.sa_flags = 0;

    if(sigaction(SIGQUIT, &newact, NULL) == -1)
	perror("Could not install handler for SIGQUIT");

    sigemptyset(&newmask);
    sigaddset(&newmask, SIGQUIT); 

    /* block SIGQUIT and save current mask*/
    if(sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
	perror("SIG_BLOCK error");
    }

    sleep(10); /* SIG_QUIT will be pending if sent */

    if(sigpending(&pendmask) < 0)
	perror("sigpending error");
    if(sigismember(&pendmask, SIGQUIT))
	printf("SIGQUIT pending\n");
    
    /* reset the signal mask to unblock SIGQUIT */
    if(sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
	perror("SIG_SETMASK error");

    printf("SIGQUIT  unblocked\n");

    sleep(10);  /* SIGQUIT will terminate here */
    exit(0);
}
