2011-10-12 93 views
1

有誰知道爲什麼運行下面的代碼可能導致所有未來的read()調用該fd(這是stdin)立即返回0而不是輸入阻塞?在標準輸入讀取()返回EOF而不是等待輸入

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

刪除tcsetattr行使read()按預期工作。

也試過:

fcntl(inFd, F_SETFL, 0); 

沒有運氣。

請注意,我目前有2個不同的終端。在其中一個應用程序中運行會導致讀取立即返回。在其他原因中運行讀取以阻止輸入。會是什麼呢?

在此先感謝:-)

攝製來源:

#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; 
} 

回答

0

我覺得你的問題是屏蔽掉ICANON,這反過來又關閉規範模式(允許非規範方式)。根據termios(3)的聯機幫助頁:

「在非規範模式下,輸入立即可用(無需用戶輸入行分隔符),並禁用了行編輯。

爲了避免混亂這篇文章,請參閱手冊頁,因爲它詳細解釋了這種行爲。當read沒有任何返回時(如在異步模式下),會發生以下行爲。記住

從toptal工程蓋爾蓋伊

0

記住,tty驅動保持從串行線已經閱讀並沒有傳遞給用戶的字節 的輸入隊列,所以不 每個read()調用等待對於實際的I/O - 讀取很可能是直接從輸入隊列滿足的 。

參考here