Search code examples
ckeypress

breaking loop with keypress in linux c


I need to write a program in C language which will be doing something like this: For example, when I will press "a", terminal will be writing that typed character in the unending loop like this: aaaaaaaaaaaaaaaa...until another key, for example "b" will be pressed. Final output should look like this: aaaaaaaaabbbbbbq (q should terminate the program). My code here:

int main(int argc, char** argv) {

    int c;
    static struct termios staryTermios, novyTermios;


    tcgetattr(STDIN_FILENO, &staryTermios);

    novyTermios = staryTermios;
    novyTermios.c_lflag &= ~(ICANON);
    tcsetattr(STDIN_FILENO, TCSANOW, &novyTermios);
    while ((c = getchar()) != 'q') {
        putchar(c);
    }

    tcsetattr( STDIN_FILENO, TCSANOW, &staryTermios);

    return 0;
}

this version writes the typed characters only once and then it waits for another keypress


Solution

  • I guess you will need two threads which will both be accessing a common variable. The job of one thread would be to continuously print the common variable. The job of the second would be to wait for input from the keyboard and update the variable accordingly.