Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reading limit of function 'read' in 'unistd.h'?

Tags:

file

io

unix

Standard unix C has this function:

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

But what is the maximum bytes that this 'read' function can read 1 time?

like image 552
jondinham Avatar asked Sep 08 '11 14:09

jondinham


People also ask

What does the read () function do?

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. For example, lseek() allows the file offset to be set beyond the end of existing data in the file.

Is read () a system call?

The "read()" system call reads data from a open file. Its syntax is exactly the same as that of the "write()" call: read( <file descriptor>, <buffer>, <buffer length> ); The "read()" function returns the number of bytes it actually returns.

What is read return EOF?

Upon reading end-of-file, zero is returned. Otherwise, a -1 is returned and the global variable errno is set to indicate the error.

Is read system call blocking?

Because client socket is configured to be nonblocking, read is incapable of blocking.


2 Answers

From man read(2):

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

If count is zero, read() returns zero and has no other results. If count is greater than SSIZE_MAX, the result is unspecified.

The value of SSIZE_MAX depends on your system, but generally it's something akin to the maximum value of signed long, which is often 231 (32-bit systems) or 263 (64-bit systems).

231 bytes is 2 gigabytes, so you're probably safe; in practice, the actual device driver/buffers/network I/O is never going to give you a 2 gigabyte chunk of data in one go.

like image 86
Lightness Races in Orbit Avatar answered Nov 26 '22 18:11

Lightness Races in Orbit


Generally it can read as many bytes as there are available in buf. In reality, the underlying device driver (be it the filesystem or the network, or a pipe), would return less than what you want in case there is nothing more available.

So, the particular behaviour of read depends on the underlying driver in the kernel.

This is why it's important to always check the return value of read and examine the actual bytes read.

like image 33
Blagovest Buyukliev Avatar answered Nov 26 '22 17:11

Blagovest Buyukliev