c - stdin 上的 read() 返回 EOF 而不是等待输入

标签 c stdin termios

有谁知道为什么运行以下代码可能会导致所有 future 对该 fd(即标准输入)的 read() 调用立即返回 0 而不是阻塞输入?

termios newTerminalSettings;
tcgetattr(inFd, &newTerminalSettings);
newTerminalSettings.c_lflag &= ~ICANON;
tcsetattr(inFd, TCSANOW, &newTerminalSettings);

删除 tcsetattr 行使 read() 按预期工作。

还试过:

fcntl(inFd, F_SETFL, 0);

没有运气。

请注意,我目前有 2 个不同的终端。在其中一个中运行应用程序会导致读取立即返回。在 other 中运行它会导致 read 阻塞输入。会是什么?

提前致谢:-)

复制来源:

#include <iostream>
#include <termios.h>

using namespace std;

int main(void) {
    termios newTerminalSettings;
    tcgetattr(0, &newTerminalSettings);
    newTerminalSettings.c_lflag &= ~ICANON;
    tcsetattr(0, TCSANOW, &newTerminalSettings);

    char readBuf[5000];
    cout << "read returned: " << read(0, readBuf, sizeof(readBuf));

    return 0;
}

最佳答案

我认为您的问题是屏蔽了 ICANON,ICANON 又关闭了规范模式(启用非规范模式)。根据 termios(3) 的联机帮助页:

“在非规范模式下,输入立即可用(用户无需键入行定界符),并且禁用行编辑。”

为避免这篇文章困惑,请参阅手册页,因为它详细解释了此行为。当 read 没有返回值时(如在异步模式下),会发生以下行为。

Gergely 来自 toptal Engineering

关于c - stdin 上的 read() 返回 EOF 而不是等待输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735884/

相关文章:

python - Python中select()之间的键盘输入

c - Linux termios 非规范 read() 超时不起作用

c - 是否有必要在 C 预处理器中检查宏的定义?

c - 如何删除C语言中字符串(字符数组)中的所有数据?

bash - 如何在 bash 脚本中 fork /管道标准输入?

Perl STDIN 在后台挂起,在前台工作正常

linux - termios.c_cflag 中的 CLOCAL 和 CRTSCTS 标志如何影响串行端口?

python - Linux:通过管道传输到 Python (ncurses) 脚本、stdin 和 termios

c - fopen、fprintf、fclose 的单行代码?

c - C中的顺序输入