/* fibtime.c * * Neal Nelson 2009.11.04 * * Set the real interval timer to 0.1 and then repeatedly accumulate its value * from the sighandler handler on each 0.1 sec interrupt. * Use the timer to see how long fib(n) takes. * * Usage: ./a.out fibnum * * */ #include #include /* for pause() */ #include #include #include /* Prototypes must occur before sig handlers are referenced */ static void itimer_handler(int); unsigned long fib(unsigned int n); /* Initialize the real time accumulator */ static long real_count = 0; main(int argc, char *argv[]) { int i; unsigned long thefib; struct itimerval real; if (argc != 2) { printf("usage: ./a.out fibnum\n"); exit(-1); } /* Register the itimer_handler to catch SIGALRM, SIGVTALRM, SIGPROF */ if (signal(SIGALRM, itimer_handler) == SIG_ERR) printf("Parent: Unable to create handler for SIGALRM\n"); /* Initialize the real itimers to one tenth of a second*/ real.it_interval.tv_sec = 0; real.it_interval.tv_usec = 99999; real.it_value.tv_sec = 0; real.it_value.tv_usec = 99999; setitimer(ITIMER_REAL, &real, NULL); /* thefib = fib(40); */ thefib = fib(atoi(argv[1])); printf("fib: %ld real_count: %ld\n", thefib, real_count); } static void itimer_handler(int signo) { switch(signo) { case SIGALRM: real_count++; printf("Parent: received SIGALRM signal, real_count: %ld\n",real_count); break; default: break; /* should never get here */ } return; } unsigned long fib(unsigned int n) { if (n == 0) return 0; else if (n == 1 || n == 2) return 1; else return (fib(n-1) + fib(n-2)); }