Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read(fd, NULL, 0); what does it do? is it well-defined?

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".

like image 729
Dima Tisnek Avatar asked Apr 16 '14 14:04

Dima Tisnek


People also ask

What does FD 0 mean?

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.

What does read () do in C?

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.

What does the read function return?

Definition and Usage. The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.

What does FD mean in Linux?

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.


1 Answers

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, ...

like image 71
Sergey L. Avatar answered Sep 26 '22 04:09

Sergey L.