How to capture Control+D signal?

As others have already said, to handle Control+D, handle “end of file”s.

Control+D is a piece of communication between the user and the pseudo-file that you see as stdin. It does not mean specifically “end of file”, but more generally “flush the input I typed so far”. Flushing means that any read() call on stdin in your program returns with the length of the input typed since the last flush. If the line is nonempty, the input becomes available to your program although the user did not type “return” yet. If the line is empty, then read() returns with zero, and that is interpreted as “end of file”.

So when using Control+D to end a program, it only works at the beginning of a line, or if you do it twice (first time to flush, second time for read() to return zero).

Try it:

$ cat
foo
   (type Control-D once)
foofoo (read has returned "foo")
   (type Control-D again)
$

Leave a Comment