我正在看看'less'工具的代碼,特別是它如何獲得鍵盤輸入。有趣的是,ttyin.c的80線,它設置文件描述符閱讀:獲取stderr的鍵盤輸入較少?
/*
* Try /dev/tty.
* If that doesn't work, use file descriptor 2,
* which in Unix is usually attached to the screen,
* but also usually lets you read from the keyboard.
*/
#if OS2
/* The __open() system call translates "/dev/tty" to "con". */
tty = __open("/dev/tty", OPEN_READ);
#else
tty = open("/dev/tty", OPEN_READ);
#endif
if (tty < 0)
tty = 2;
是不是文件描述符2標準錯誤?如果是這樣,WTH ?!我認爲鍵盤輸入是通過stdin發送的。
有趣的是,即使你ls -l * | less
,文件加載完畢後,你仍然可以使用鍵盤上下滾動,但如果這樣做ls -l * | vi
,然後六將在罵你,因爲它不會從標準輸入讀取。什麼是大想法?我怎麼最終在這個陌生的新土地上出現了stderr既是向屏幕報告錯誤又從鍵盤讀取數據的方式?我不認爲我在堪薩斯州...
順便說一句,如果你寫'ls -l * | vim -',vim會執行類似的魔法。 – ephemient 2011-02-07 14:31:59