read() from stdin

后端 未结 5 1467
有刺的猬
有刺的猬 2020-12-09 17:21

Consider the following line of code:

while((n = read(STDIN_FILENO, buff, BUFSIZ)) > 0)

As per my understanding read/write f

5条回答
  •  春和景丽
    2020-12-09 17:53

    1. read attempts to get all of characters requested.
    2. if EOF happens before all of the requested characters can be returned, it returns what it got after it does this the next read returns -1, to let you know you the file end.

    What happens when it tries to read and there is nothing there involves something called blocking. You can call open to read a file blocking or non-blocking. "blocking" means wait until there is something to return.

    This is what you see in a shell waiting for input. It sits there. Until you hit return.

    Non-blocking means that read will return no bytes of data if there are none. Depending on a lot of other factors which would make a completely correct answer unusable for you, read will set errno to something like EWOULDBLOCK, which lets you know why your read returned zero bytes. It is not necessarily a fatal error.

    Your code could test for a minus to find EOF or errors

提交回复
热议问题