/*------------------------------------------------------------------*/ /* testalarmtimeout.c */ /* The alarm function to implement a timeout. */ /* Author: Bob Dondero */ /*------------------------------------------------------------------*/ #define _GNU_SOURCE #include #include #include #include #include /*------------------------------------------------------------------*/ static void myHandler(int iSig) /* This function is intended to be a handler for signals of type SIGALRM. Print a timeout message to stdout, and exit. */ { printf("\nSorry. You took too long.\n"); exit(EXIT_FAILURE); } /*------------------------------------------------------------------*/ int main(void) /* Illustrate using an alarm to cause a timeout. */ { int i; void (*pfRet)(int); sigset_t sSet; int iRet; /* Make sure that SIGALRM is not blocked. */ sigemptyset(&sSet); sigaddset(&sSet, SIGALRM); iRet = sigprocmask(SIG_UNBLOCK, &sSet, NULL); assert(iRet == 0); pfRet = signal(SIGALRM, myHandler); assert(pfRet != SIG_ERR); printf("Enter a number: "); alarm(5); scanf("%d", &i); alarm(0); printf("You entered the number %d.\n", i); return 0; }