Pergunta

I am trying to make a loop that will run infinitely without user input, until 'Enter' is pressed. This is the simplified version of my program:

do {

printf("Hello\n");

}while(!getchar());

When I compile and run the program only output one 'Hello' and the program will not continue, until Enter is pressed then the program will exit. May I know which part am I wrong?

Thank you.

Foi útil?

Solução

It is not so easy. Your problem is that the standard I/O functions are synchronous. Your getchar is waiting for some input (a line of input to be precise) and it blocks execution of program until Enter is pressed. To continue execution without blocking you need to use asynchronous I/O operations or select (or poll). Select allows you to detect whether the next I/O operation would block or not. Look at the documentation of select and try this:

#include<stdio.h>
#include<unistd.h>
#include <sys/select.h>

int main() {
    fd_set          s;
    struct timeval  timeout;

    timeout.tv_sec = 0;
    timeout.tv_usec = 100000;

    do {
        printf("Hello\n"); 
        fflush(stdout);
        FD_ZERO(&s);
        FD_SET(STDIN_FILENO, &s);
        select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);
    } while (FD_ISSET(STDIN_FILENO, &s) == 0);

}

Outras dicas

Your program gets stucked because getchar() function is awaiting for input. When you input something (enter), getchar() returns non-zero value, so the while statement becomes wrong and thats why the loop is ended.

On Linux, the terminal is a tty which is generally somehow buffered by the kernel. Read the tty demystified and about line discipline.

You might use ncurses or readline

Read getchar(3) man page (e.g. with man 3 getchar in a terminal). It says that

getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

So your test is wrong, you probably want while(getchar() != EOF) which does not wait for some keyboard input. In other words getchar is always blocking on user input. You could give an end-of-file with Ctrl D

need to figure out difference of Canonical vs. non-canonical terminal input

As you tried i think on canonical terminal so what's limitation you already now.So i just explain you about non-canonical terminal

For non-canonical input - think vi or vim or whatever — you press a character, and it is immediately available to the program. You aren't held up until you hit return. The system does no editing of the characters; they are made available to the program as soon as they are typed. It is up to the program to interpret things appropriately. Now, vim does do a number of things that look a bit like canonical input. For example, backspace moves backwards, and in input mode erases what was there. But that's because vim chooses to make it behave like that.

So you need to use non-canonical flavor.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top