下面的代碼是一個非阻塞讀取terminal
IO的示例,但是當我在控制檯上鍵入字符時,它不會立即將其打印出來。 Perpaps你會說我應該私下設置stty -icanon
,所以canonical模式被禁用,確實有效,但我認爲即使我沒有禁用stty icanon
,非阻塞讀終端是character-oriented
,cannonical
模式只是喚醒阻塞過程,但我的進程沒有阻塞,如果我們鍵入一個字符,那麼fd是可讀的,所以它應該立即打印出字符。如果規範模式未設置,非阻塞讀取失敗?
#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;
}