#include #include #include #include #include #define COUNT 10 int right = 0; int wrong = 0; bool timed_out; void SIGALRM_handler(int signo); int main(void) { struct itimerval tval; char string[BUFSIZ]; timerclear(&tval.it_interval); timerclear(&tval.it_value); tval.it_value.tv_sec = 2; // 2 second timeout signal(SIGALRM, SIGALRM_handler); for (int k = 1; k <= COUNT; k++) { int i = rand()%10; int j = rand()%10; printf("Problem #%d: Solve %d+%d=", k, i, j); timed_out = false; setitimer(ITIMER_REAL, &tval, NULL); // set timer if (fgets(string, sizeof string, stdin) != NULL) { if (!timed_out) { setitimer(ITIMER_REAL, NULL, NULL); // turn off timer if (atoi(string) == i + j) { right++; printf("Correct!\n"); } else { wrong++; printf("Wrong!\n"); } } } } printf("\nRight: %d, wrong: %d\n", right, wrong); return 0; } void SIGALRM_handler(int sig) { printf("\nTime's up!\nPress return for another problem.\n"); wrong++; timed_out = true; }