/*-------------------------------------------------------------------*/ /* testalarmtimeout.c */ /* Author: Bob Dondero */ /* The alarm system call to implement a timeout. */ /*-------------------------------------------------------------------*/ #define _GNU_SOURCE #include #include #include #include /*-------------------------------------------------------------------*/ static void myHandler(int iSignal) /* 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(int argc, char *argv[]) /* Illustrate using an alarm to cause a timeout. */ { int i; void (*pfRet)(int); sigset_t sSigSet; int iRet; /* Make sure that SIGALRM is not blocked. */ sigemptyset(&sSigSet); sigaddset(&sSigSet, SIGALRM); iRet = sigprocmask(SIG_UNBLOCK, &sSigSet, NULL); if (iRet != 0) {perror(argv[0]); exit(EXIT_FAILURE); } /* Install myHandler as the handler for SIGALRM signals. */ pfRet = signal(SIGALRM, myHandler); if (pfRet == SIG_ERR) {perror(argv[0]); exit(EXIT_FAILURE); } printf("Enter a number: "); alarm(5); scanf("%d", &i); alarm(0); printf("You entered the number %d.\n", i); return 0; } /* Sample execution: $ gcc217 testalarmtimeout.c -o testalarmtimeout $ testalarmtimeout Enter a number: 123 You entered the number 123. $ testalarmtimeout Enter a number: Sorry. You took too long. */