I am attempting to write a program that will set an alarm for 10 seconds, block the SIGINT after that 10 seconds, set another alarm for 10 seconds, unblock and ignore SIGINT after that, set another alarm for 10 seconds then terminate. I was hoping I could just do all of the operations within an sa_handler for SIGALRM but it isn't working as I had hoped. Is it at all possible to do this? Edit: when in the sa-handler of SIGALRM i am unable to set the SIGINT to blocked.
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
int ctrlct = 0;
int alrmct = 0;
void catchctrlc(int signo)
{
printf("Caught CTRL-C! <%d>\n", ++ctrlct);
}
void catchalrm(int signo)
{
sigset_t alrmset;
switch(alrmct)
{
case 0:
printf("Alarm 1\n");
if( (sigemptyset(&alrmset) == -1) || (sigaddset(&alrmset, SIGINT) == -1) )
printf("Failed to add SIGINT to the alrmset");
else if( sigprocmask(SIG_BLOCK, &alrmset, NULL) == -1 )
printf("Failed to block SIGINT");
break;
case 1:
printf("Alarm 2\n");
break;
case 2:
printf("Alarm 3\n");
exit(EXIT_SUCCESS);
break;
default:
break;
}
alrmct++;
alarm(10);
}
int main(void)
{
struct sigaction ctrlact, alrmact;
ctrlact.sa_handler = catchctrlc;
ctrlact.sa_flags = 0;
alrmact.sa_handler = catchalrm;
alrmact.sa_flags = 0;
/* Install signal handler for CTRL-C */
if((sigemptyset(&ctrlact.sa_mask) == -1) || (sigaction(SIGINT, &ctrlact, NULL) == -1))
perror("Failed to set sa_handler for SIGINT");
/* Install signal handler for SIGALRM */
if((sigemptyset(&alrmact.sa_mask) == -1) || (sigaction(SIGALRM, &alrmact, NULL)== -1))
perror("Failed to set sa_handler for SIGALRM");
alarm(10);
while(1){}
return 0;
}