/* * ISA 563, Spring 2011 * Copyleft by Muhammad Abdulla */ #include #include #include #include #include /* * alarm.c -- demonstrates an practical use of alarm function. */ enum { FAILURE, SUCCESS } ; void alarm_handler(int signo) { printf("Operation timed out. Exiting...\n\n"); exit(0); } int check_user(char *uname, int umax) { int ulen; char *valid_chars = "abcdefghijklmnopqrstuvwxyz1234567890"; fprintf(stdout, "Enter your user name: "); fflush(stdout); alarm(20); // set off alarm so that we will receive SIGALRM in 20 seconds if( fgets(uname, umax, stdin) == NULL ) { // alarm(0); // turn off alert before we return (try commenting off this) return FAILURE; } alarm(0); // turn off alert before we return ulen = strlen(uname); if ( uname[ulen - 1] == '\n' ) { // chop off the newline character uname[--ulen] = '\0'; } // username characters should be alphanumeric, and should not start with a digit if ( (ulen == 0) || isdigit(uname[0]) || (ulen != strspn(uname, valid_chars)) ) { return FAILURE; } return SUCCESS; } int main ( int argc, char *argv[] ) { char uname[64]; signal(SIGALRM, alarm_handler); if ( check_user(uname, sizeof(uname)) == FAILURE ) { printf("User name is invalid.\n"); } else { printf("User name is valid.\n"); } printf("Waiting something to happen ...\n"); pause(); }