Quantcast
Channel: Coding and Programing » Uncategorized
Viewing all articles
Browse latest Browse all 10

capture Control+D signal

$
0
0

Problem And Question

I want to capture the Control+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.

Best Solution And Answer

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

Viewing all articles
Browse latest Browse all 10

Trending Articles