简体   繁体   中英

Under what circumstances does the read() syscall return 0?

I'm looking at the read syscall in Unix, which (at least in Linux) has this signature: [1]

ssize_t read(int fd, void* buf, size_t count);

Let's assume that the call succeeds (ie no negative return values) and that count > 0 (ie the buffer actually can store a nonzero amount of bytes). Under which circumstances would read() return 0? I can think of the following:

  • When fd refers to a regular file and the end of the file has been reached.
  • When fd refers to the receiving end of a pipe, socket or FIFO, the sending end has been closed and the pipe's/socket's/FIFO's own buffer has been exhausted.
  • When fd refers to the slave side of a terminal device that is in ICANON and Ctrl-D has been sent into the master side while the line buffer was empty.

I'm curious if there are any other situations that I'm not aware of, where read() would return with a result of 0. I'm especially interested (because of reasons) in situations like the last one in the list above, where read() returns 0 once, but subsequent calls to read() on the same FD could return a nonzero result. If an answer only applies to a certain flavor of Unix, I'm still interested in hearing it.

[1] I know this signature is for the libc wrapper, not the actual syscall, but that's not important right now.

  • If the Physical File System does not support simple reads from directories, read() will return 0 if it is used for a directory.
  • If no process has the pipe open for writing, read() returns 0 to indicate the end of the file.
  • If the connection is broken on a stream socket, but no data is available, then the read() function returns 0 bytes as EOF.

Normally a return value of 0 always means end-of-file. However, if you specify 0 as the number of bytes to read, it will always return 0 unless there's an error detected.

Terminal devices are a special case. If the terminal is in cooked mode, typing Control-d tells the device driver to return from any pending read() immediately with whatever is in the input editing buffer, rather than waiting for the user to enter a newline. If the buffer is empty, this results in a zero-length read. This is how typing the EOF character at the beginning of a line is automatically treated as EOF by applications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM