3

I am reading character from command prompt, and checking for EOF for termination of program.
But when I am giving command Ctrl+D it is not taking as a EOF. Kindly specify what to do for it.

Ctrl+C is working, which terminate the entire process.

  • 2
    How are you checking for EOF? Working sample of code, please, which should you edit into your question. – roaima Oct 20 '15 at 8:08
  • 1
    Please also post the output of stty. Does Ctrl-D work with cat? What do you mean by reading character from command prompt? – Stéphane Chazelas Oct 20 '15 at 11:06
2

Assuming tty "cooked" mode, ctrl-D works by terminating line input processing and sending the data already entered to the application. So if you type "abc" followed by ctrl-D those three bytes will be sent off to the application.

Now, how does an application generally determine end-of-file? EOF is assumed when a read returns 0 bytes. So you need to cause a read to return 0 bytes. If you first hit enter and then ctrl-D, first anything you typed is sent to the application together with the newline character. Then the ctrl-D causes any data you entered (i.e. nothing!) to be sent to the application, which reads 0 bytes, and assumes EOF.

If you enter anything after the enter before hitting ctrl-D then the application gets those keystrokes, and waits for more. So to generate EOF without first hitting enter, hit ctrl-D twice in a row.

So to answer your question: did you first enter any characters (besides newline) before hitting ctrl-D? If so, try it twice in succession.

This can be tested with e.g.:

$ wc -l
test123     0     1     7

(hit ctrl-D twice after the test123.)

The wc utility shows the number of lines, words and characters read. Lines is 0 because you didn't enter a newline, and test123 is one word and 7 characters long.

1

There is no "EOF character", ctrl-D is translated by the terminal driver into the end-of-file condition, transmitted to whoever is trying to read past that (without it, a read(2) or other input expecting call will just wait forever for more input). This depends on the mode the tty is in, the preceding discussion applies to cooked mode (the driver collects lines, allowing a limited form of line editing, full lines are shipped to the reader). Cooked mode is the default, used by most every program reading form the keyboard. In raw mode (the one e.g. vi(1) or other editors set to get complete control) the program gets each character exactly as typed.

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.