The code below is an example of a non-blocking reading of terminal IO, however, when I type in a character on the console, it does not immediately print it. Perpapses, you will say that I have to set stty -icanon , so canonical mode is disabled, which really works, but I think that even if I donβt disable stty icanon , non-blocking terminal reading is a character-oriented , cannonical mode just wakes up the blocking process but my process does not block, if we enter a character, then we read fd, so it should immediately print the character.
#include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #define MSG_TRY "try again\n" int main(void) { char buf[10]; int fd, n; fd = open("/dev/tty", O_RDONLY|O_NONBLOCK); if(fd<0) { perror("open /dev/tty"); exit(1); } tryagain: n = read(fd, buf, 10); if (n < 0) { if (errno == EAGAIN) { sleep(1); write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY)); goto tryagain; } perror("read /dev/tty"); exit(1); } write(STDOUT_FILENO, buf, n); close(fd); return 0; }
source share