#include /* standard I/O functions */ #include /* standard unix functions, like getpid() */ #include /* signal name macros, and the signal() prototype */ #define GOOD_PASSWORD "marvelous" /* password we're expecting to get */ /* define values for 'YES' and 'NO' */ #ifndef YES # define YES 1 # define NO 0 #endif /* this function switches echo mode on or off. in off mode, nothing */ /* the user types is echoed on the screen (e.g. when typing a password). */ /* note: we're using the 'stty' command to switch the mode. there are */ /* cleaner ways, but we don't want to complicate things now. */ void echo_on(int is_it) { if (is_it == YES) system("stty echo"); else system("stty -echo"); } /* here is the signal handler. it switches the input mode to echo-on, */ /* then suspends the process using a STOP signal. Once the process's */ /* operation is resumed, the function continues right after the call to */ /* the kill() function, sets echo mode off, and reproduces the password */ /* prompt, so the user will know that we're still expecting a password. */ void catch_suspend(int sig_num) { /* re-set the signal handler again to catch_int, for next time */ signal(SIGTSTP, catch_suspend); printf("Suspending execution...\n"); fflush(stdout); /* re-enable echo mode, so the user can keep on working.. */ echo_on(YES); kill(getpid(), SIGSTOP); /* ... we'll get back here when the process is resumed... */ printf("Resuming execution, please hold on...\n"); /* disable echo mode again. */ echo_on(NO); /* reproduce the prompt, so the users will remember */ /* where they suspended the program. */ printf("Password: "); fflush(stdout); } /* and the main function goes here */ int main(int argc, char* argv[]) { char user[30]; /* user name supplied by the user */ char passwd[30]; /* password supplied by the user */ /* prompt the user for a user name */ printf("Username: "); fflush(stdout); /* wait for input */ gets(user); /* set the TSTP (Ctrl-Z) signal handler to 'catch_suspend' */ signal(SIGTSTP, catch_suspend); /* prompt the user for a password */ printf("Password: "); fflush(stdout); /* set input to no-echo mode, so what the user types */ /* won't be shown on screen. */ echo_on(NO); /* wait for input */ gets(passwd); /* re-enable echo on input */ echo_on(YES); /* print a new-line, since the ENTER pressed by the user was not echoec */ printf("\n"); fflush(stdout); /* switch the TSTP signal handler to its default behaviour */ signal(SIGTSTP, SIG_DFL); /* and now, do something with the password */ if (strcmp(passwd, GOOD_PASSWORD) == 0) printf("Access granted.\n"); else printf("Access denied.\n"); return 0; }