Under What Circumstances Does The Read() Syscall Return 0

Can read(2) return zero when not at EOF?

Figured it out! I had an Uninitialized Memory Read (UMR) and was incorrectly seeking to the end of the file.

Will reading from a pipe ever produce more data after a prior EOF?

Yes. read on the same FD will start returning data again if something reopens the pipe for writing.

You can easily reopen named pipes, and Linux lets you reopen anonymous pipes by writing to /proc/<pid>/fd/<fd> . In particular, you can open this file for writing even if the FD is only open for reading in the process that you're getting it from.

Understanding read syscall

Is it guaranteed that if read returns the number of bytes read less then I requested then the next call to read will return 0?

No, not in practice. It should be true if the file system is entirely POSIX compliant, but many of them are not (in corner cases). In particular NFS (see nfs(5)) and FUSE or proc (see proc(5)) are not exactly POSIX compliant.

So in practice I strongly recommend handling the "read returns a smaller number of bytes than wanted case", even if you are right to believe that it should not happen. Handling that "impossible" case should be easy for you.

Notice also that inotify(7) facilities don't work with bizarre filesystems like NFS, proc, FUSE, ... Think also of corner cases like, inside an Ext4 file system, a symlink to an NFS file,; or bind mounts, etc...

Call read() returns 0 but buffer changed, not happened when call fread() to read the same offset

I think I've found what's going on here.
The file is a binary one, but I read() it with text mode(O_RDONLY).

The value of offset 10315001 is 0x1a, when read() and fread() function meets 0x1a in text mode, they both will return 0, but the different is, the read() will still write the buf with binary mode, while fread() won't do this.



Related Topics



Leave a reply



Submit