我正在查看“less”实用程序的代码,特别是它如何获取键盘输入。有趣的是,在 ttyin.c 的第 80 行,它将文件描述符设置为从以下位置读取:
/*
* 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 stderr 吗?如果是这样,WTH?!我认为键盘输入是通过标准输入发送的。
有趣的是,即使你这样做ls -l * | less
了,在文件加载完成后,你仍然可以使用键盘上下滚动,但如果你这样做了ls -l * | vi
,那么 vi 就会对你大喊大叫,因为它不是从 stdin 读取的。有什么大主意?我是如何进入这个陌生的新领域的,stderr 既是向屏幕报告错误又是从键盘读取的一种方式?我想我已经不在堪萨斯了...