I am writing a small C program that asks a user for a password, as the user enters characters via keyboard, these characters will be displayed as asterisks and when they hit enter the actual password is displayed. I have tried fiddling with getchar() and assigning variables but I am not getting the desired solution. Any guidance is appreciated, thanks.
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <string.h>
char *get_password();
int main() {
struct termios info;
tcgetattr(0, &info);
// info.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &info);
printf("Create a password: ");
int c = getchar();
c = '*';
char *password = get_password();
printf("You entered: %s\n", password);
tcgetattr(0, &info);
info.c_lflag |= ECHO;
tcsetattr(0, TCSANOW, &info);
}
#define BUFSIZE 100
char buf[BUFSIZE];
char *get_password() {
int c, len = 0;
while ((c = getchar()) != EOF && c != '\n') {
buf[len++] = c;
if (len == BUFSIZE - 1)
break;
}
buf[len] = 0;
putchar('\n');
return buf;
}
As #chqrlie points out, proper password processing requires that echoing be disabled and buffering as well. Here are the quick steps to do that:
#include <termios.h>
#include <sys/ioctl.h>
struct termios termstat;
tcgetattr(STDIN_FILENO,&termstat);
termstat.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO,TCSANOW,&termstat);
then after you're done with the password handling, restore the normal behavior with:
termstat.c_lflag |= (ICANON | ECHO);
tcsetattr(STDIN_FILENO,TCSANOW,&termstat);
Reading a password without echo is a bit more tricky than just fiddling with getchar():
you must disable the buffering in stdin or read bytes directly from the low level system handle 0*;
you must temporarily disable the terminal echo and buffering features, using system dependent API calls;
to avoid leaving the terminal in a bad state, you should also disable signal processing and handle the signal characters explicitly;
upon reading the bytes from handle 0, you must output stars and flush the output to the terminal;
you should handle the backspace key as users will expect to be able to correct typing errors;
you must restore the terminal state after input completes.
*) Reading from system handle 2 (stderr) is a useful alternative to get the password from the user even if stdin is redirected from a file.
Here is a commented implementation:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
char *get_password(void) {
struct termios info, save;
static char buf[100];
size_t len = 0;
char c;
int res;
tcgetattr(0, &info);
save = info;
/* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */
info.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP |
INLCR | IGNCR | ICRNL | IXON);
/* output modes - disable post processing */
info.c_oflag &= ~(OPOST);
/* local modes - echoing off, canonical off, no extended functions,
* no signal chars (^Z,^C) */
info.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG);
/* control modes - set 8 bit chars, disable parity handling */
info.c_cflag &= ~(CSIZE | PARENB);
info.c_cflag |= CS8;
/* control chars - set return condition: min number of bytes and timer.
* We want read to return every single byte, without timeout. */
info.c_cc[VMIN] = 1; /* 1 byte */
info.c_cc[VTIME] = 0; /* no timer */
tcsetattr(0, TCSANOW, &info);
for (;;) {
fflush(stdout);
/* read a single byte from stdin, bypassing stream handling */
res = read(0, &c, 1);
if (res != 1) {
/* special case EINTR and restart */
if (res == -1 && errno == EINTR)
continue;
/* other cases: read failure or end of file */
break;
}
if (c == '\n' || c == '\r') {
/* user hit enter */
break;
}
if (c == '\b' || c == 127) {
/* user hit the backspace or delete key */
if (len > 0) {
printf("\b \b");
len--;
}
continue;
}
if (c == 3) {
/* user hit ^C: should abort the program */
tcsetattr(0, TCSANOW, &save);
printf("^C\n");
fflush(stdout);
return NULL;
}
if (c < ' ') {
/* ignore other control characters */
continue;
}
if (len >= sizeof(buf) - 1) {
putchar(7); /* beep */
} else {
putchar('*');
buf[len++] = c;
}
}
tcsetattr(0, TCSANOW, &save);
putchar('\n');
fflush(stdout);
buf[len] = '\0';
return buf;
}
int main() {
char *password;
printf("Create a password: ");
password = get_password();
if (password) {
printf("You entered: %s\n", password);
} else {
printf("You hit ^C, program aborted\n");
return 1;
}
return 0;
}
I want to mask my password while writing it with *.
I use Linux GCC for this code.
I know one solution is to use getch() function like this
#include <conio.h>
int main()
{
char c,password[10];
int i;
while( (c=getch())!= '\n');{
password[i] = c;
printf("*");
i++;
}
return 1;
}
but the problem is that GCC does not include conio.h file so, getch() is useless for me.
Does anyone have a solution?
In the Linux world, masking isn't usually done with asterisks, normally echoing is just turned off and the terminal displays blanks E.g. if you use su or log into a virtual terminal etc.
There is a library function to handle getting passwords, it won't mask the password with asterisks but will disable echoing of the password to terminal. I pulled this out of a linux book I have. I believe its part of the posix standard
#include <unistd.h>
char *getpass(const char *prompt);
/*Returns pointer to statically allocated input password string
on success, or NULL on error*/
The getpass() function first disables echoing and all processing of
terminal special characters (such as the interrupt character, normally
Control-C).
It then prints the string pointed to by prompt, and reads a line of
input, returning the null-terminated input string with the trailing
newline stripped, as its function result.
A google search for getpass() has a reference to the GNU implementation (should be in most linux distros) and some sample code for implementing your own if need be
http://www.gnu.org/s/hello/manual/libc/getpass.html
Their example for rolling your own:
#include <termios.h>
#include <stdio.h>
ssize_t
my_getpass (char **lineptr, size_t *n, FILE *stream)
{
struct termios old, new;
int nread;
/* Turn echoing off and fail if we can't. */
if (tcgetattr (fileno (stream), &old) != 0)
return -1;
new = old;
new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stream), TCSAFLUSH, &new) != 0)
return -1;
/* Read the password. */
nread = getline (lineptr, n, stream);
/* Restore terminal. */
(void) tcsetattr (fileno (stream), TCSAFLUSH, &old);
return nread;
}
If need be you could use this as the basis as modify it to display asterisks.
Without getch to rely on and avoiding the obsolete getpass, the recommended approach is to disable terminal ECHO through termios use. After a few searches to find a canned flexible password routine, I was surprised that very few for stand-alone use with C. Rather than simply recoding getch with termios c_lflag options, slightly more generalized approach takes just a few additions. Beyond replacing getch any routine should enforce a specified maximum length to prevent overflow, truncate if the user attempt to enter beyond the maximum, and warn if truncation occurs in some manner.
Below, the additions will allow reading from any FILE * input stream, limiting the length to a specified length, provide minimal editing (backspace) ability when taking input, allow the character mask to be specified or disabled completely, and finally return the length of the password entered. A warning was added when the password entered was truncated to the maximum or specified length.
Hopefully it will prove useful to others with this question looking for a similar solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#define MAXPW 32
/* read a string from fp into pw masking keypress with mask char.
getpasswd will read upto sz - 1 chars into pw, null-terminating
the resulting string. On success, the number of characters in
pw are returned, -1 otherwise.
*/
ssize_t getpasswd (char **pw, size_t sz, int mask, FILE *fp)
{
if (!pw || !sz || !fp) return -1; /* validate input */
#ifdef MAXPW
if (sz > MAXPW) sz = MAXPW;
#endif
if (*pw == NULL) { /* reallocate if no address */
void *tmp = realloc (*pw, sz * sizeof **pw);
if (!tmp)
return -1;
memset (tmp, 0, sz); /* initialize memory to 0 */
*pw = (char*) tmp;
}
size_t idx = 0; /* index, number of chars in read */
int c = 0;
struct termios old_kbd_mode; /* orig keyboard settings */
struct termios new_kbd_mode;
if (tcgetattr (0, &old_kbd_mode)) { /* save orig settings */
fprintf (stderr, "%s() error: tcgetattr failed.\n", __func__);
return -1;
} /* copy old to new */
memcpy (&new_kbd_mode, &old_kbd_mode, sizeof(struct termios));
new_kbd_mode.c_lflag &= ~(ICANON | ECHO); /* new kbd flags */
new_kbd_mode.c_cc[VTIME] = 0;
new_kbd_mode.c_cc[VMIN] = 1;
if (tcsetattr (0, TCSANOW, &new_kbd_mode)) {
fprintf (stderr, "%s() error: tcsetattr failed.\n", __func__);
return -1;
}
/* read chars from fp, mask if valid char specified */
while (((c = fgetc (fp)) != '\n' && c != EOF && idx < sz - 1) ||
(idx == sz - 1 && c == 127))
{
if (c != 127) {
if (31 < mask && mask < 127) /* valid ascii char */
fputc (mask, stdout);
(*pw)[idx++] = c;
}
else if (idx > 0) { /* handle backspace (del) */
if (31 < mask && mask < 127) {
fputc (0x8, stdout);
fputc (' ', stdout);
fputc (0x8, stdout);
}
(*pw)[--idx] = 0;
}
}
(*pw)[idx] = 0; /* null-terminate */
/* reset original keyboard */
if (tcsetattr (0, TCSANOW, &old_kbd_mode)) {
fprintf (stderr, "%s() error: tcsetattr failed.\n", __func__);
return -1;
}
if (idx == sz - 1 && c != '\n') /* warn if pw truncated */
fprintf (stderr, " (%s() warning: truncated at %zu chars.)\n",
__func__, sz - 1);
return idx; /* number of chars in passwd */
}
A simple program showing the use would be as follows. If using a static array of character for holding the password, just insure a pointer is passed to the function.
int main (void ) {
char pw[MAXPW] = {0};
char *p = pw;
FILE *fp = stdin;
ssize_t nchr = 0;
printf ( "\n Enter password: ");
nchr = getpasswd (&p, MAXPW, '*', fp);
printf ("\n you entered : %s (%zu chars)\n", p, nchr);
printf ( "\n Enter password: ");
nchr = getpasswd (&p, MAXPW, 0, fp);
printf ("\n you entered : %s (%zu chars)\n\n", p, nchr);
return 0;
}
Example Output
$ ./bin/getpasswd2
Enter password: ******
you entered : 123456 (6 chars)
Enter password:
you entered : abcdef (6 chars)
The functionality of getch (which is a non-standard, Windows function) can be emulated with this code:
#include <termios.h>
#include <unistd.h>
int getch() {
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
Note that your approach is not perfect - it's better to use something like ncurses or another terminal library to handle these things.
You can create your own getch() function on Linux in this manner.
int getch() {
struct termios oldtc, newtc;
int ch;
tcgetattr(STDIN_FILENO, &oldtc);
newtc = oldtc;
newtc.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newtc);
ch=getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldtc);
return ch;
}
Demo code:
int main(int argc, char **argv) {
int ch;
printf("Press x to exit.\n\n");
for (;;) {
ch = getch();
printf("ch = %c (%d)\n", ch, ch);
if(ch == 'x')
break;
}
return 0;
}
Your method is correct, however you'll need to turn off terminal echo while the password is being entered:
#include <sgtty.h>
void echo_off()
{
struct sgttyb state;
(void)ioctl(0, (int)TIOCGETP, (char *)&state);
state.sg_flags &= ~ECHO;
(void)ioctl(0, (int)TIOCSETP, (char *)&state);
}
void echo_on()
{
struct sgttyb state;
(void)ioctl(0, (int)TIOCGETP, (char *)&state);
state.sg_flags |= ECHO;
(void)ioctl(0, (int)TIOCSETP, (char *)&state);
}
Instead of getch(), why not just use getc() instead?
Thanks all of you whose help & support to solve my problem.
I find a best way to hide my password in linux that fits me best.
To use getpass() function. It just need to include "unistd.h" file.
syntex of getpass function:
char * getpass (const char *prompt)
Parameters:
prompt: string pointer to print while asking for Password
Return Value:
string pointer of password
Example:
#include <stdio.h>
#include <unistd.h>
int main()
{
char *password; // password string pointer
password = getpass("Enter Password: "); // get a password
printf("%s\n",password); // this is just for conformation
// that password stored successfully
return 1;
}
output:
Enter Password:
heet
You might use ncurses.h if it is not necessary to be portable onto Windows for that, but here is some kind of a more "portable" version:
If it is not necessery to be portable ill point you to a ncurses solution
portablegetch.h
/*portablegetch.h*/
#ifndef PGETCH
#define PGETCH
#ifdef __unix__
#include <termios.h>
#include <unistd.h>
static struct termios n_term;
static struct termios o_term;
static int
cbreak(int fd)
{
if((tcgetattr(fd, &o_term)) == -1)
return -1;
n_term = o_term;
n_term.c_lflag = n_term.c_lflag & ~(ECHO|ICANON);
n_term.c_cc[VMIN] = 1;
n_term.c_cc[VTIME]= 0;
if((tcsetattr(fd, TCSAFLUSH, &n_term)) == -1)
return -1;
return 1;
}
int
getch()
{
int cinput;
if(cbreak(STDIN_FILENO) == -1) {
fprintf(stderr, "cbreak failure, exiting \n");
exit(EXIT_FAILURE);
}
cinput = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &o_term);
return cinput;
}
#elif _MSC_VER || __WIN32__ || __MS_DOS__
#include <conio.h>
#endif
#endif
And the c-file
whatever.c
#include <stdio.h>
#include <stdlib.h>
#include "portablegetch.h"
int
main(int argc, char **argv)
{
int input;
printf("Please Enter your Password:\t");
while(( input=getch() ) != '\n')
printf("*");
printf("\n");
return EXIT_SUCCESS;
}
That should fit to your problem.
Hope that helps.
#include <termios.h>
#include <stdio.h>
static struct termios old, new;
void initTermios(int echo) {
tcgetattr(0, &old);
new = old;
new.c_lflag &= ~ICANON;
new.c_lflag &= echo ? ECHO : ~ECHO;
tcsetattr(0, TCSANOW, &new);
}
void resetTermios(void) {
tcsetattr(0, TCSANOW, &old);
}
char getch_(int echo) {
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
char getch(void) {
return getch_(0);
}
int main(void) {
char c;
printf("(getch example) please type a letter...");
c = getch();
printf("\nYou typed: %c\n", c);
return 0;
}
Just copy these snippet and use it. Hope it helped
Just pass for it the char* that you want to set password in and its size and the function will do its job
void set_Password(char *get_in, int sz){
for (int i = 0; i < sz;) {
char ch = getch();
if (ch == 13) {
get_in[i] = '\0';
break;
}
else if(ch != 8){
get_in[i++] = ch;
putch('*');
}
else if(i > 0)
cout << "\b \b",get_in[i--] = '\0';
}
cout << "\n";
}
This is an example, run it on your compiler
Unfortunately in the C standard library there is no such function out of the box. Maybe in third party library.
One option is use ANSI escape sequences to set the background color to foreground color in the console to conceal the password. Try this link.
With scanning the characters you can take it into a buffer. Also you need to write code if backspace is pressed, and appropriately correct the inserted password.
Here is a code which once i wrote with the curses. Compile with gcc file.c -o pass_prog -lcurses
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#define ENOUGH_SIZE 256
#define ECHO_ON 1
#define ECHO_OFF 0
#define BACK_SPACE 127
char *my_getpass (int echo_state);
int main (void)
{
char *pass;
initscr ();
printw ("Enter Password: ");
pass = my_getpass (ECHO_ON);
printw ("\nEntered Password: %s", pass);
refresh ();
getch ();
endwin ();
return 0;
}
char *my_getpass (int echo_state)
{
char *pass, c;
int i=0;
pass = malloc (sizeof (char) * ENOUGH_SIZE);
if (pass == NULL)
{
perror ("Exit");
exit (1);
}
cbreak ();
noecho ();
while ((c=getch()) != '\n')
{
if (c == BACK_SPACE)
{
/* Do not let the buffer underflow */
if (i > 0)
{
i--;
if (echo_state == ECHO_ON)
printw ("\b \b");
}
}
else if (c == '\t')
; /* Ignore tabs */
else
{
pass[i] = c;
i = (i >= ENOUGH_SIZE) ? ENOUGH_SIZE - 1 : i+1;
if (echo_state == ECHO_ON)
printw ("*");
}
}
echo ();
nocbreak ();
/* Terminate the password string with NUL */
pass[i] = '\0';
endwin ();
return pass;
}
In C you can use getpasswd() function which pretty much doing similar thing as stty in shell, example:
#include <stdio.h>
#include <string.h>
#include <pwd.h>
#include <unistd.h>
int main()
{
char acct[80], password[80];
printf(“Account: “);
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);
return 0;
}
Here is equivalent shell script which use stty (which changes the settings of your tty):
save_state=$(stty -g)
/bin/echo -n “Account: “
read acct
/bin/echo -n “Password: “
stty -echo
read password # this won’t echo
stty “$save_state”
echo “”
echo account = $acct and password = $password
Source: How can I read a password without echoing it in C?
man getpass
This function is obsolete. Do not use it. If you want to read input
without terminal echoing enabled, see the description of the ECHO flag
in termios(3)
# include <termios.h>
# include <unistd.h> /* needed for STDIN_FILENO which is an int file descriptor */
struct termios tp, save;
tcgetattr( STDIN_FILENO, &tp); /* get existing terminal properties */
save = tp; /* save existing terminal properties */
tp.c_lflag &= ~ECHO; /* only cause terminal echo off */
tcsetattr( STDIN_FILENO, TCSAFLUSH, &tp ); /* set terminal settings */
/*
now input by user in terminal will not be displayed
and cursor will not move
*/
tcsetattr( STDIN_FILENO, TCSANOW, &save); /* restore original terminal settings */
If you notice, most current linux distro's do not mask a password with asterisks. Doing so divulges the length of the password which is no way beneficial. It is easier and better to simply make the cursor not move when a password is typed in. If for whatever reason you require a * to be printed for every character that's typed then you would have to grab every keypress before Enter is hit and that's always been problematic.
printf("\nENTER PASSWORD: ");
while (1)
{
ch=getch();
if(ch==13) //ON ENTER PRESS
break;
else if(ch==8) //ON BACKSPACE PRESS REMOVES CHARACTER
{
if(i>0)
{
i--;
password[i]='\0';
printf("\b \b");
}
}
else if (ch==32 || ch==9) //ON PRESSING TAB OR SPACE KEY
continue;
else
{
password[i]=ch;
i++;
printf("*");
}
}
password[i]='\0';
Here is my idea, adapted from that of the C++ official site.
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
string getpass(const char *prompt, bool showchar = false, char echochar = '*')
{
struct termios oi, ni;
tcgetattr(STDIN_FILENO, &oi);
ni = oi;
ni.c_lflag &= ~(ICANON | ECHO);
const char DELETE = 127;
const char RETURN = 10;
string password;
unsigned char ch = 0;
cout << prompt;
tcsetattr(STDIN_FILENO, TCSANOW, &ni);
while (getchar() != RETURN) {
if (ch == DELETE) {
if(password.length != 0){
if (showchar) cout << "\b \b";
password.resize(password.length() - 1);
}
}else {
password += getchar();
if (showchar) cout << echochar;
}
}
tcsetattr(STDIN_FILENO,TCSANOW,&oi)
cout << endl;
return password;
}
It will read one character at once and add it to the string and supports showing another character.
note that the ICANON termios lflag turns off the processing carriagereturn/linefeed, and the negative ECHO termios setting turns off echo for STDIN.
when using this (with or without the echo being on) to read a password and print '*' for entered characters, it's not just a matter of reading characters until a newline/carriage return is encountered, you also have to process backspace in your 'string building routine' (else the backspaces end up in the actual string, and do not cause characters to be removed from it such as would be the case with the various string based input functions).
the same would happen in C in DOS with getch tho. that would also happily return 0x08 for backspace (or 127 or whatever your specific os uses as backspace)
keeping track of 'not deleting -before- the start of the string', replacing the 'new end of the string' with 0 and moving the current position counter back by one (unless you are at position 0) is up to the programmer with any of these functions (even the getch on dos C).
getpass() doesn't do what the user originally asked for btw, he wants *'s (which still disclose the length of the password to people standing behind him and looking at his screen, as well as in the scrollbuffer of the terminal if he doesn't close it after use). but without *'s is probably a better idea in 'non closed environments'.
#include <stdio.h>
/* copy input to output */
main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
return 0;
}
In the given code, the program displays the input character.
It reads every character one by one (into the variable 'c') and outputs the same read characters simultaneously. The program terminates when the EOF character is given as input.
When I ran the code in my IDE (Code::Blocks 16.01) and input a string,
eg: Hi! My name is C.\n
The output is displayed after '\n' and not simultaneously.
Isn't the output supposed to be as - "HHii!! MMyy nnaammee iiss CC.."?
Bold letters indicate the output.
include:
#include <unistd.h>
#include <termios.h>
before your code in main insert:
struct termios term, term_orig;
if(tcgetattr(STDIN_FILENO, &term_orig)) {
printf("tcgetattr failed\n");
return -1;
}
term = term_orig;
term.c_lflag &= ~ICANON;
if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) {
printf("tcsetattr failed\n");
return -1;
}
after your code insert:
if (tcsetattr(STDIN_FILENO, TCSANOW, &term_orig)) {
printf("tcsetattr failed\n");
return -1;
}
Because by default, input from terminal is line-buffered. So your program get a whole line after you press Enter.
To disable buffering in Unix & Linux systems, try this:
#include <unistd.h>
#include <termios.h>
int disableLineBuffer(void){
struct termios term, oldterm;
if (tcgetattr(STDIN_FILENO, &term)) return -1;
oldterm = term;
term.c_lflag &= ~(ECHO | ICANON);
if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) return -1;
return 0;
}
In Windows, go and do this instead:
#include <windows.h>
BOOL WINAPI DisableLineBuffer(void){
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
if (!GetConsoleMode(hInput, &mode)) return FALSE;
mode &= ~ENABLE_LINE_INPUT;
if (!SetConsoleMode(hInput, mode)) return FALSE;
return TRUE;
}
Be sure to revert changes to the console before your program exits, or you may have trouble doing anything else in your terminal.
I'm using Linux console and I would like to do a program which outputs random characters until ESC is pressed. How can I make such a keyboard handler?
The line discipline for a terminal device often works in canonical mode by default. In this mode, the terminal driver doesn't present the buffer to userspace until the newline is seen (Enter key is pressed).
You can set the terminal into raw (non-canonical) mode by using tcsetattr() to manipulate the termios structure. Clearing the ECHO and ICANON flags respectively disables echoing of characters as they are typed and causes read requests to be satisfied directly from the input queue. Setting the values of VTIME and VMIN to zero in the c_cc array causes the read request (fgetc()) to return immediately rather than block; effectively polling stdin. The call to fgetc() will return EOF if a character is not available in the stream.
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <time.h>
int getkey() {
int character;
struct termios orig_term_attr;
struct termios new_term_attr;
/* set the terminal to raw mode */
tcgetattr(fileno(stdin), &orig_term_attr);
memcpy(&new_term_attr, &orig_term_attr, sizeof(struct termios));
new_term_attr.c_lflag &= ~(ECHO|ICANON);
new_term_attr.c_cc[VTIME] = 0;
new_term_attr.c_cc[VMIN] = 0;
tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);
/* read a character from the stdin stream without blocking */
/* returns EOF (-1) if no character is available */
character = fgetc(stdin);
/* restore the original terminal attributes */
tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
return character;
}
int main()
{
int key;
/* initialize the random number generator */
srand(time(NULL));
for (;;) {
key = getkey();
/* terminate loop on ESC (0x1B) or Ctrl-D (0x04) on STDIN */
if (key == 0x1B || key == 0x04) {
break;
}
else {
/* print random ASCII character between 0x20 - 0x7F */
key = (rand() % 0x7F);
printf("%c", ((key < 0x20) ? (key + 0x20) : key));
}
}
return 0;
}
Note: This code omits error checking for simplicity.
change the tty settings for one key press:
int getch(void) {
int c=0;
struct termios org_opts, new_opts;
int res=0;
//----- store old settings -----------
res=tcgetattr(STDIN_FILENO, &org_opts);
assert(res==0);
//---- set new terminal parms --------
memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c=getchar();
//------ restore old settings ---------
res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
assert(res==0);
return(c);
}
getch() from Curses library perhaps? Also, you will need to use notimeout() to tell getch() not to wait for next keypress.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
char * me = "Parent";
void sigkill(int signum)
{
//printf("=== %s EXIT SIGNAL %d ===\n", me, signum);
exit(0);
}
main()
{
int pid = fork();
signal(SIGINT, sigkill);
signal(SIGQUIT, sigkill);
signal(SIGTERM, sigkill);
if(pid == 0) //IF CHILD
{
int ch;
me = "Child";
while(1)
{
ch = (rand() % 26) + 'A'; // limit range to ascii A-Z
printf("%c",ch);
fflush(stdout); // flush output buffer
sleep(2); // don't overwhelm
if (1 == getppid())
{
printf("=== CHILD EXIT SINCE PARENT DIED ===\n");
exit(0);
}
}
printf("==CHILD EXIT NORMAL==\n");
}
else //PARENT PROCESS
{
int ch;
if((ch = getchar())==27)
kill(pid, SIGINT);
//printf("==PARENT EXIT NORMAL (ch=%d)==\n", ch);
}
return(0);
}
In this program u will only need to press enter after esc char,because getchar()is a blocking function.
Also u may remove or decrease sleep time for child process as ur need.
while(ch != 'q')
{
printf("looping\n");
sleep(1);
if(kbhit())
{
ch = readch();
printf("you hit %c\n",ch);
}
}
This code gives me a blocking getch() like functionality. I am trying to use this code to capture up down arrow keys.
Added:
Trying to capture key codes of up arrow gives me 3 chars 27, 91 and 65.
Using if/else I am trying pattern matching but I only get 2 chars. Next one is captured when next key is pressed.
I want to capture full words using getchar() while always looking for certain keys all the time(esc, del etc.).
I can't reproduce Your problem:
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include "kbhit.h" /* http://linux-sxs.org/programming/kbhit.html */
int main(){
init_keyboard();
char ch='x';
while( ch != 'q' ){
printf("looping\n");
sleep(1);
if( kbhit() ){
printf("you hit");
do{
ch = readch();
printf(" '%c'(%i)", isprint(ch)?ch:'?', (int)ch );
}while( kbhit() );
puts("");
}
}
close_keyboard();
}
This example could help:
raw.c - raw mode demonstration
/* Raw mode demo */
/* See exactly what is being transmitted from the terminal. To do this
we have to be more careful. */
#include <stdio.h>
#include <signal.h>
#include <termios.h>
#include <stdlib.h>
#include <unistd.h>
struct termios oldtermios;
int ttyraw(int fd)
{
/* Set terminal mode as follows:
Noncanonical mode - turn off ICANON.
Turn off signal-generation (ISIG)
including BREAK character (BRKINT).
Turn off any possible preprocessing of input (IEXTEN).
Turn ECHO mode off.
Disable CR-to-NL mapping on input.
Disable input parity detection (INPCK).
Disable stripping of eighth bit on input (ISTRIP).
Disable flow control (IXON).
Use eight bit characters (CS8).
Disable parity checking (PARENB).
Disable any implementation-dependent output processing (OPOST).
One byte at a time input (MIN=1, TIME=0).
*/
struct termios newtermios;
if(tcgetattr(fd, &oldtermios) < 0)
return(-1);
newtermios = oldtermios;
newtermios.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* OK, why IEXTEN? If IEXTEN is on, the DISCARD character
is recognized and is not passed to the process. This
character causes output to be suspended until another
DISCARD is received. The DSUSP character for job control,
the LNEXT character that removes any special meaning of
the following character, the REPRINT character, and some
others are also in this category.
*/
newtermios.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
/* If an input character arrives with the wrong parity, then INPCK
is checked. If this flag is set, then IGNPAR is checked
to see if input bytes with parity errors should be ignored.
If it shouldn't be ignored, then PARMRK determines what
character sequence the process will actually see.
When we turn off IXON, the start and stop characters can be read.
*/
newtermios.c_cflag &= ~(CSIZE | PARENB);
/* CSIZE is a mask that determines the number of bits per byte.
PARENB enables parity checking on input and parity generation
on output.
*/
newtermios.c_cflag |= CS8;
/* Set 8 bits per character. */
newtermios.c_oflag &= ~(OPOST);
/* This includes things like expanding tabs to spaces. */
newtermios.c_cc[VMIN] = 1;
newtermios.c_cc[VTIME] = 0;
/* You tell me why TCSAFLUSH. */
if(tcsetattr(fd, TCSAFLUSH, &newtermios) < 0)
return(-1);
return(0);
}
int ttyreset(int fd)
{
if(tcsetattr(fd, TCSAFLUSH, &oldtermios) < 0)
return(-1);
return(0);
}
void sigcatch(int sig)
{
ttyreset(0);
exit(0);
}
int main()
{
int i;
char c;
/* Catch the most popular signals. */
if((int) signal(SIGINT,sigcatch) < 0)
{
perror("signal");
exit(1);
}
if((int)signal(SIGQUIT,sigcatch) < 0)
{
perror("signal");
exit(1);
}
if((int) signal(SIGTERM,sigcatch) < 0)
{
perror("signal");
exit(1);
}
/* Set raw mode on stdin. */
if(ttyraw(0) < 0)
{
fprintf(stderr,"Can't go to raw mode.\n");
exit(1);
}
while( (i = read(0, &c, 1)) == 1)
{
if( (c &= 255) == 0177) /* ASCII DELETE */
break;
printf( "%o\n\r", c);
}
if(ttyreset(0) < 0)
{
fprintf(stderr, "Cannot reset terminal!\n");
exit(-1);
}
if( i < 0)
{
fprintf(stderr,"Read error.\n");
exit(-1);
}
return 0;
}
(backspace to stop the demo, origin)