为什么需要按两次 ^D 才能退出 `cat`?

Igo*_*nko 13 tty pty stty

让我们运行cat然后输入athen ^D- 你会看到cat没有退出。

cat+ a+ Enter+比较^D- 现在 cat 确实退出了。

那么,为什么在第一种情况下^D需要按两次退出cat,而^D在第二种情况下只需要按一次?

cam*_*amh 25

答案可以在termios(3)手册页中找到:

   VEOF   (004, EOT, Ctrl-D) End-of-file character (EOF).  More precisely:
          this character causes the pending tty buffer to be sent  to  the
          waiting  user program without waiting for end-of-line.  If it is
          the first character of the line, the read(2) in the user program
          returns  0, which signifies end-of-file.  Recognized when ICANON
          is set, and then not passed as input.
Run Code Online (Sandbox Code Playgroud)

第一个^D你按下使你键入要传递到线cat,所以它得到read(2)的结果a(一个字符,没有EOL字符)。第二个^D原因read(2)返回 0,这表示 EOF 到cat

  • @IgorLiferenko bash(和其他一些 shell)对 `^D` 有两种不同的响应,因为它们试图遵循两个不同的先例:没有行编辑能力的古代 shell 的行为就像 `cat`,并在 EOF 上退出,但编辑器喜欢将 `^D` 用于其他目的(例如 emacs 中的“删除光标下的字符”)。当在空行上输入字符时将其解释为退出命令,否则将其删除,这是一种效果很好的折衷方案(因为当没有字符时您无法删除字符) (3认同)