Search code examples
cstdinread-write

Understanding read + write in c


char buf[1];
if (argc == 1) {
    while (read(STDIN_FILENO, buf, 1) > 0) {
        write(1, buf, sizeof(buf));
    }
}

I have a few things I'd like to clarify about this snippet. We run it, ./exec_file Let's say we just press Enter. We move to the next line and read 1 byte '\n' then write it to stdout bringing us down one more line... simple enough. Now lets say we type h, then Enter. The program spits out h on the next line with an invisible '\n'.

Looking at the code after we type h it reads it into the buffer then writes it to stdout but somehow the program waits to spit it out on the next line till after I've pressed Enter..how?

Lastly, when we first hit the while loop wouldn't read initially return 0 since we haven't typed anything in initially??


Solution

  • stdin behaves a bit different than most other streams.

    First, input is line buffered. That means that input isn't available until you press enter. this explains while the h won't appear until you press enter.

    Since it is a stream it doesn't really have an end. Instead of failing when there is no data to read, the call will block until some data is available (or until the program receives a signal). A socket works the same way.

    The blocking behaviour can be turned off using fcntl :

    int fd = STDIN_FILENO;
    int flags = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, flags | O_NONBLOCK);