0

I'm trying to write a program that works like a UNIX terminal. So when Ctrl+D is pressed, it should exit. I'm reading input using:

char input[BUFFER_SIZE];
read(0, input, BUFFER_SIZE)

I'm also storing the output like this:

int num_read = read(0, input, BUFFER_SIZE);
//`read` is called only once. like this ^^^

Now I'm doing this to check CTRL+D:

if (num_read == 0)
{
    exit(CTRL_D_EXIT);
}

Now the question is how can I catch, CTRL+D, after some input? Like I've types asdasdas and then CTRL+D. Then I want to sound some alarm, or print a new line. How can I do so?

In my case, it just goes on executing the rest of the block as usual (size is not 0).

And here is a reference to Ctrl+D having a 0 size: https://stackoverflow.com/a/1516152/10305444

Yun
  • 3,056
  • 6
  • 9
  • 28
Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
  • 2
    Ctrl+D registers as `EOF` when it's the first keystroke after an ENTER. Otherwise you need 2 Ctrl+Ds (note that Ctrl-D in the middle of the buffer is hard to catch). – pmg Sep 13 '21 at 06:32
  • 2
    Unrelated: if you're treating `input` as a string (`strlen()`, `printf()`, ...) you need to add the terminating `'\0'` manually: `read()` does not add it. – pmg Sep 13 '21 at 06:34

0 Answers0