I've seen following statement in a few programs, most/all seem to be made for Linux.
rv = read(fd, NULL, 0);
In some programs it's in a loop, in some a single statement.
What does it do really?
Man page says that an invocation like this may or may not check for errors...
What is the significance of return value?
What types of file descriptors are supported?
And if rv==0
how to distinguish "no error" from e.g. "socket closed".
At the file descriptor level, stdin is defined to be file descriptor 0, stdout is defined to be file descriptor 1; and stderr is defined to be file descriptor 2.
The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() shall return bytes with value 0.
Definition and Usage. The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.
In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier (handle) for a file or other input/output resource, such as a pipe or network socket.
This call will do all the usual error checking on the file descriptor, but not retrieve any data from it. This is useful if you wish to for example determine if the file descriptor is still valid without blocking on it.
It will return -1
if an error occurs and 0
otherwise. Most of the errors listed in man 2 read
can be queried in this way and will be returned in errno
.
For example a return value of -1
and errno
of EBADF
will be retuned if the file descriptor is closed. Instead return value will be 0
if everything is good and another read
will not return an error that is associated with the validity of the file descriptor.
A subsequent read
with a real buffer and nbyte > 0
can still generate any number of errors like ENOMEM
, EAGAIN
, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With