1

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

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

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

也试过:

fcntl(inFd, F_SETFL, 0);

没有运气。

请注意,我目前有 2 个不同的终端。在其中一个中运行应用程序会导致 read 立即返回。在其他情况下运行它会导致 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;
}
4

2 回答 2

0

请记住,tty 驱动程序维护一个已从串行线路读取但未传递给用户的字节输入队列,因此并非每个 read() 调用都等待实际 I/O - 读取很可能直接从输入队列。

参考这里

于 2011-11-06T13:08:42.483 回答
0

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

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

为避免使这篇文章混乱,请参阅手册页,因为它详细解释了这种行为。当 read 没有返回任何内容时(如在异步模式下),会发生以下行为。

来自 toptal Engineering 的 Gergely

于 2011-11-06T12:54:30.540 回答