#include #include #include #include #include /* * getpw2.c: get a password with echo off * shows how to use signal to catch ^C and reset terminal before exit */ int turn_off_echo(int); int turn_on_echo(int); int read_a_string(int , char [], int ); void intr_handler(int); #define SLEN 100 int main() { char str[SLEN]; signal(SIGINT, intr_handler); if ( turn_off_echo(0) == -1 ) /* fd 0 is stdin */ exit(1); if ( read_a_string(0, str, SLEN) == 0 ) printf("You typed the string: %s\n", str); if ( turn_on_echo(0) == -1 ) exit(1); return 0; } /* called when user presses Ctrl-C */ void intr_handler(int s) { printf("interrupted! restoring echo state.\n"); turn_on_echo(0); exit(1); } /* * read no more than len-1 chars into array, put a \0 at end * if last char is a \n, then remove that */ int read_a_string(int fd, char a[], int len) { int nread; nread = read(fd, a, len-1); if ( nread <= 0 ) return -1; if ( a[nread-1] == '\n' ) a[nread-1] = '\0'; else a[nread] = '\0'; return 0; } /* * get settings for fd, turn off the ECHO bit, set settings */ int turn_off_echo(int fd) { struct termios settings; if ( tcgetattr(fd, &settings) == -1 ) return -1; settings.c_lflag &= ~ECHO; /* turn off echo bit */ if ( tcsetattr(fd, TCSANOW, &settings) == -1 ) return -1; return 0; } /* * get settings for fd, turn on the ECHO bit, set settings */ int turn_on_echo(int fd) { struct termios settings; if ( tcgetattr(fd, &settings) == -1 ) return -1; settings.c_lflag |= ECHO; /* turn off echo bit */ if ( tcsetattr(fd, TCSANOW, &settings) == -1 ) return -1; return 0; }