有谁知道为什么运行以下代码可能会导致所有 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/