How to capture Control+D signal?

Ryan picture Ryan · Oct 4, 2009 · Viewed 82.3k times · Source

I want to capture the Ctrl+D signal in my program and write a signal handler for it. How can I do that? I am working on C and using a Linux system.

Answer

Pascal Cuoq picture Pascal Cuoq · Oct 4, 2009

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)
$