I’m trying to figure out how to disable the echo flag in C. I want to do this because I am coding a C program that must ask for a users password, so I would like to disable Echo, let the user enter his password, then re-enable Echo.
Before I show you the solution in C, I want to start by demonstrating how to do this in a shell script, because they both demonstrate how to solve the problem and they both show that the solution is to learn just a bit about the keyboard device driver.
Specifically, we Unix old-timers refer to it as the tty, quite literally teletypewriter or teletype device. Think late 60’s clattering printer / keyboard hooked up via a thick wire to a computational device the size of a small washing machine and you’d be on the money.
This device name is still around, and in fact the keyboard driver is still called the “tty”. Try it, type tty on the command line in Linux:
Amazing, isn’t it? Thirty years later…
On the Linux command line, the utility that lets you change the settings of this “tty” command is stty, and here’s exactly how you could use this to turn off echo temporarily in a shell script to ask for a password:
/bin/echo -n “Account: “
/bin/echo -n “Password: “
read password # this won’t echo
echo account = $acct and password = $password
When run, it looks like this:
account = test and password = demo
Now, finally, let’s convert that to a C program.
Fortunately, there’s a very useful function in C that’s widely available called getpasswd() which does all the “stty” heavy lifting. It makes things easy:
char acct, password;
fgets(acct, 80, stdin);
acct[strlen(acct)-1] = 0; /* remove carriage return */
strncpy(password, getpass(“Password: “), 80);
printf(“You entered acct %s and pass %s\n”, acct, password);
If you want to do something more sophisticated where you output an asterisk each time they enter a character, you can check out some of the example code on the Ubuntu forums discussion.