0

I opened cat without any argument in the terminal:

cat

And then I typed some text and pressed Ctrl+D, and what I typed was echoed back.

I re-typed some text and pressed Enter, and what I typed was also echoed back.

Is there a difference between Ctrl+D and Enter (I am talking about when there is text in the terminal when pressing one of these keys, because when there is no text, Ctrl+D sends EOF, while Enter does not).

1

enter makes the terminal device line discipline send the current input buffer plus \n (translated from the \r sent by the terminal (emulator) by the icrnl setting of the line discipline) to the application which is reading from the terminal device. ^D makes the terminal device line discipline send the current input buffer without a \n nor ^D character (the character is eaten away by the line discipline unless you sent ^V beforehand).

Pressing ^D twice in a row makes cat exit because it assumes there is nothing more to read (read() returns 0 byte).

| improve this answer | |
  • Pressing ^D only one time made cat exit based on my testing (unless you mean pressing ^D twice when there is text in the terminal). – user258851 Nov 3 '17 at 15:17
  • @HaukeLaging This is correct but incomplete. ^D is the default eof setting for the line discipline. When eof is detected as the first character in the read buffer the current application doing the read exits. When it's detected but isn't the first character the line is flushed. This is true for at least readline and libedit. Proof: after stty eof ^T it's ^T that has that effect described above, and ^D has no effect. – Satō Katsura Nov 3 '17 at 15:50
  • @user258851 If you have not typed anything (after the last <enter>) then you have the same situation as if you had pressed ^D before. Thus you need only one ^D to make cat exit. – Hauke Laging Nov 3 '17 at 16:16
  • @SatōKatsura There is no difference on the side of the terminal: In both cases it sends the current buffer to the application (i.e. has (read() return). But usually applications exit when read() returns zero bytes. The read() does not even return with an error. – Hauke Laging Nov 3 '17 at 16:22
  • What I'm saying is ^D behave this way because it's stty eof, not because it's ^D. Also, AFAICT this behavior is incidental. If you think for 5 minutes how a line editing function should be implemented given the UNIX functions, that's the straightforward way and it also makes sense. Which is why shells do that. But to the best of my knowledge only "exit when eof on input" is mandated by standards. It's in principle possible to have a line editing library that doesn't flush the buffer when it sees eof. FWIW. – Satō Katsura Nov 3 '17 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.