READ(3P)
๐ PROLOG ๐
okay so bestie, this page is part of the POSIX Programmer's Manual โ yes, the whole READ(3P) situation. Heads up: the Linux implementation of this interface may differ (so go consult the corresponding Linux manual page for the tea on Linux behavior), or the interface may not even be implemented on Linux. Not me being dramatic, that's just what it says. ๐
โจ NAME โจ
pread, read โ read from a file. That's the vibe. Two functions, one mission: get bytes out of a file. ๐ซถ
๐ SYNOPSIS ๐
#include <unistd.h>
ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
ssize_t read(int fildes, void *buf, size_t nbyte);
๐ฆ DESCRIPTION ๐ฆ
Okay so here's the whole lore. The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. And the behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified โ so like, don't expect a cute predictable answer there. ๐
Before any action described below is taken, and if nbyte is zero, the read() function may detect and return errors as described below. In the absence of errors, or if error detection is not performed, the read() function shall return zero and have no other results. So zero bytes in? Maybe zero out, maybe error check, but no other results. periodt.
On files that support seeking (for example, a regular file), the read() shall start at a position in the file given by the file offset associated with fildes. The file offset shall be incremented by the number of bytes actually read. So it moves the cursor, basically. ๐
Files that do not support seekingโfor example, terminalsโalways read from the current position. The value of a file offset associated with such a file is undefined. So don't come for it, there is no defined offset. ๐
No data transfer shall occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 shall be returned. If the file refers to a device special file, the result of subsequent read() requests is implementation-defined. So that's a "depends on your implementation" moment, bestie. ๐ง
If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-defined. Again: implementation says what it says. โจ
When attempting to read from an empty pipe or FIFO:
- If no process has the pipe open for writing,
read()shall return0to indicate end-of-file. bye, no writers. ๐ - If some process has the pipe open for writing and
O_NONBLOCKis set,read()shall return-1and seterrnoto[EAGAIN]. Not today, try again later. ๐ญ - If some process has the pipe open for writing and
O_NONBLOCKis clear,read()shall block the calling thread until some data is written or the pipe is closed by all processes that had the pipe open for writing. So it's giving "wait for it..." ๐
When attempting to read a file (other than a pipe or FIFO) that supports non-blocking reads and has no data currently available:
- If
O_NONBLOCKis set,read()shall return-1and seterrnoto[EAGAIN]. same energy. - If
O_NONBLOCKis clear,read()shall block the calling thread until some data becomes available. nap time until data arrives. ๐ด - The use of the
O_NONBLOCKflag has no effect if there is some data available. like, it literally doesn't matter then. ๐คท
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. If data is later written at this point, subsequent reads in the gap between the previous end of data and the newly written data shall return bytes with value 0 until data is written into the gap. So holes read as zeros. iconic, honestly. ๐ณ๏ธ
Upon successful completion, where nbyte is greater than 0, read() shall mark for update the last data access timestamp of the file, and shall return the number of bytes read. This number shall never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data. So it can be a short read, and that's valid. no cap. ๐
If a read() is interrupted by a signal before it reads any data, it shall return -1 with errno set to [EINTR]. rude, but okay. ๐ค
If a read() is interrupted by a signal after it has successfully read some data, it shall return the number of bytes read. so partial data still counts. ๐
For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with fildes. respect the limit. ๐
If fildes refers to a socket, read() shall be equivalent to recv() with no flags set. socket behavior said "same as recv(), no flags." ๐
If the O_DSYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If the O_SYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion. synchronization lore, periodt. โก
If fildes refers to a shared memory object, the result of the read() function is unspecified. If fildes refers to a typed memory object, the result of the read() function is unspecified. so like, undefined vibes. ๐
A read() from a STREAMS file can read data in three different modes: byte-stream mode, message-nondiscard mode, and message-discard mode. The default shall be byte-stream mode. This can be changed using the I_SRDOPT ioctl() request, and can be tested with I_GRDOPT ioctl(). In byte-stream mode, read() shall retrieve data from the STREAM until as many bytes as were requested are transferred, or until there is no more data to be retrieved. Byte-stream mode ignores message boundaries. okay so mode one: byte-stream, boundaries who? ๐ฆ
In STREAMS message-nondiscard mode, read() shall retrieve data until as many bytes as were requested are transferred, or until a message boundary is reached. If read() does not retrieve all the data in a message, the remaining data shall be left on the STREAM, and can be retrieved by the next read() call. Message-discard mode also retrieves data until as many bytes as were requested are transferred, or a message boundary is reached. However, unread data remaining in a message after the read() returns shall be discarded, and shall not be available for a subsequent read(), getmsg(), or getpmsg() call. So nondiscard keeps leftovers, discard yeets them. ๐
How read() handles zero-byte STREAMS messages is determined by the current read mode setting. In byte-stream mode, read() shall accept data until it has read nbyte bytes, or until there is no more data to read, or until a zero-byte message block is encountered. The read() function shall then return the number of bytes read, and place the zero-byte message back on the STREAM to be retrieved by the next read(), getmsg(), or getpmsg(). In message-nondiscard mode or message-discard mode, a zero-byte message shall return 0 and the message shall be removed from the STREAM. When a zero-byte message is read as the first message on a STREAM, the message shall be removed from the STREAM and 0 shall be returned, regardless of the read mode. zero-byte messages are their own whole saga, bestie. ๐ญ
A read() from a STREAMS file shall return the data in the message at the front of the STREAM head read queue, regardless of the priority band of the message. front of the line energy. ๐
By default, STREAMs are in control-normal mode, in which a read() from a STREAMS file can only process messages that contain a data part but do not contain a control part. The read() shall fail if a message containing a control part is encountered at the STREAM head. This default action can be changed by placing the STREAM in either control-data mode or control-discard mode with the I_SRDOPT ioctl() command. In control-data mode, read() shall convert any control part to data and pass it to the application before passing any data part originally present in the same message. In control-discard mode, read() shall discard message control parts but return to the process any data part in the message. control modes are giving "choose your fighter." ๐
In addition, read() shall fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno shall not reflect the result of read(), but reflect the prior error. If a hangup occurs on the STREAM being read, read() shall continue to operate normally until the STREAM head read queue is empty. Thereafter, it shall return 0. so that errno is stale, and hangup means keep reading until empty, then zero. ๐
The pread() function shall be equivalent to read(), except that it shall read from a given position in the file without changing the file offset. The first three arguments to pread() are the same as read() with the addition of a fourth argument offset for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking shall result in an error. so pread() is the "read from here but don't move my cursor" bestie. and if seeking isn't possible? error. periodt. ๐
๐ RETURN VALUE ๐
Upon successful completion, these functions shall return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions shall return -1 and set errno to indicate the error. That's the whole return value tea: non-negative on success, -1 plus errno on error. ๐
๐ ERRORS ๐
okay bestie, here's the part where things go wrong and the kernel starts yelling at you. buckle up ๐
These functions shall fail if:
EAGAINโ the file is not a pipe, not a FIFO, not a socket, theO_NONBLOCKflag is set on that file descriptor, and your thread would be delayed in the read. it's giving "i could read but not right now" ๐EBADFโ thefildesargument is not a valid file descriptor open for reading. like. girl. that's not even a real fd ๐EBADMSGโ the file is a STREAM file set to control-normal mode and the message waiting to be read includes a control part.EINTRโ the read got terminated because a signal showed up, and no data was transferred.EINVALโ the STREAM or multiplexer referenced byfildesis linked (directly or indirectly) downstream from a multiplexer.EIOโ the process is a member of a background process group trying to read from its controlling terminal, and either the calling thread is blockingSIGTTIN, or the process is ignoringSIGTTIN, or the process group of the process is orphaned. this error may also be generated for implementation-defined reasons, so like, sometimes it just happens โจEISDIRโ thefildesargument refers to a directory and the implementation does not allow the directory to be read usingread()orpread(). you wantreaddir()instead, bestie. it's literally right there ๐ซถEOVERFLOWโ the file is a regular file,nbyteis greater than 0, the starting position is before the end-of-file, and the starting position is greater than or equal to the offset maximum established in the open file description associated withfildes.
The pread() function shall fail if:
EINVALโ the file is a regular file or block special file, and theoffsetargument is negative. the file offset shall remain unchanged.ESPIPEโ the file is incapable of seeking. it said no to seeking, respectfully ๐ซ
The read() function shall fail if:
EAGAINโ the file is a pipe or FIFO, theO_NONBLOCKflag is set for the file descriptor, and the thread would be delayed in the read operation.EAGAINorEWOULDBLOCKโ the file is a socket, theO_NONBLOCKflag is set for the file descriptor, and the thread would be delayed in the read operation.ECONNRESETโ a read was attempted on a socket and the connection was forcibly closed by its peer. ghosted, fr fr ๐ญENOTCONNโ a read was attempted on a socket that is not connected. not me trying to read from a socket that isn't even in a relationship ๐ETIMEDOUTโ a read was attempted on a socket and a transmission timeout occurred.
These functions may fail if:
EIOโ a physical I/O error has occurred.ENOBUFSโ insufficient resources were available in the system to perform the operation.ENOMEMโ insufficient memory was available to fulfill the request.ENXIOโ a request was made of a nonexistent device, or the request was outside the capabilities of the device.
โจ The following sections are informative. โจ (translation: the standard is basically saying "this next part is bonus content, not rules")
๐ EXAMPLES ๐
Reading Data into a Buffer ๐
the following example reads data from the file associated with the file descriptor fd into the buffer pointed to by buf. look at her go:
#include <sys/types.h>
#include <unistd.h>
...
char buf[20];
size_t nbytes;
ssize_t bytes_read;
int fd;
...
nbytes = sizeof(buf);
bytes_read = read(fd, buf, nbytes);
...
that's it. that's the whole vibe. sizeof the buffer, then read into it. slay ๐
๐ธ APPLICATION USAGE ๐ธ
None.
literally nothing. no notes. iconic behavior honestly ๐
๐ง RATIONALE ๐ง
okay so this is the "why did we do it this way" section and it's long but it's actually so good. get comfy ๐
This volume of POSIX.1โ2017 does not specify the value of the file offset after an error is returned; there are too many cases, bestie. for programming errors, such as [EBADF], the concept is meaningless since no file is involved. for errors that are detected immediately, such as [EAGAIN], clearly the offset should not change. after an interrupt or hardware error, however, an updated value would be very useful and is the behavior of many implementations. so like. it depends. classic ๐
note that a read() of zero bytes does not modify the last data access timestamp. a read() that requests more than zero bytes, but returns zero, is required to modify the last data access timestamp. the zero-byte read said "i'm not touching that timestamp" and it meant it.
implementations are allowed, but not required, to perform error checking for read() requests of zero bytes. so it might check, it might not. vibe check inconclusive ๐ฅ
Input and Output ๐ฆ
the use of I/O with large byte counts has always presented problems. ideas such as lread() and lwrite() (using and returning longs) were considered at one time. the current solution is to use abstract types on the ISO C standard function to read() and write(). the abstract types can be declared so that existing functions work, but can also be declared so that larger types can be represented in future implementations. it is presumed that whatever constraints limit the maximum range of size_t also limit portable I/O requests to the same range. this volume of POSIX.1โ2017 also limits the range further by requiring that the byte count be limited so that a signed return value remains meaningful. since the return type is also a (signed) abstract type, the byte count can be defined by the implementation to be larger than an int can hold. okay that one was a lot, but we got through it together ๐ซถ
the standard developers considered adding atomicity requirements to a pipe or FIFO, but recognized that due to the nature of pipes and FIFOs there could be no guarantee of atomicity of reads of {PIPE_BUF} or any other size that would be an aid to applications portability. they tried, bestie. they really did. ๐ญ
this volume of POSIX.1โ2017 requires that no action be taken for read() or write() when nbyte is zero. this is not intended to take precedence over detection of errors (such as invalid buffer pointers or file descriptors). this is consistent with the rest of this volume of POSIX.1โ2017, but the phrasing here could be misread to require detection of the zero case before any other errors. a value of zero is to be considered a correct value, for which the semantics are a no-op. zero is valid. zero is fine. zero is at peace โจ
I/O is intended to be atomic to ordinary files and pipes and FIFOs. atomic means that all the bytes from a single operation that started out together end up together, without interleaving from other I/O operations. it is a known attribute of terminals that this is not honored, and terminals are explicitly (and implicitly permanently) excepted, making the behavior unspecified. the behavior for other device types is also left unspecified, but the wording is intended to imply that future standards might choose to specify atomicity (or not). terminals really said "rules for thee, not for me" ๐
there were recommendations to add format parameters to read() and write() in order to handle networked transfers among heterogeneous file system and base hardware types. such a facility may be required for support by the OSI presentation of layer services. however, it was determined that this should correspond with similar C-language facilities, and that is beyond the scope of this volume of POSIX.1โ2017. the concept was suggested to the developers of the ISO C standard for their consideration as a possible area for future work. so it's a "not my department, ask ISO C" situation, no cap.
in 4.3 BSD, a read() or write() that is interrupted by a signal before transferring any data does not by default return an [EINTR] error, but is restarted. in 4.2 BSD, 4.3 BSD, and the Eighth Edition, there is an additional function, select(), whose purpose is to pause until specified activity (data to read, space to write, and so on) is detected on specified file descriptors. it is common in applications written for those systems for select() to be used before read() in situations (such as keyboard input) where interruption of I/O due to a signal is desired. history lesson served, hot ๐ฅ
the issue of which files or file types are interruptible is considered an implementation design issue. this is often affected primarily by hardware and reliability issues. so basically: your mileage may vary, and that's on purpose.
there are no references to actions taken following an ``unrecoverable error''. it is considered beyond the scope of this volume of POSIX.1โ2017 to describe what happens in the case of hardware errors. we do not talk about the unrecoverable error. we simply do not ๐
earlier versions of this standard allowed two very different behaviors with regard to the handling of interrupts. in order to minimize the resulting confusion, it was decided that POSIX.1โ2008 should support only one of these behaviors. historical practice on AT&T-derived systems was to have read() and write() return -1 and set errno to [EINTR] when interrupted after some, but not all, of the data requested had been transferred. however, the US Department of Commerce FIPS 151โ1 and FIPS 151โ2 require the historical BSD behavior, in which read() and write() return the number of bytes actually transferred before the interrupt. if -1 is returned when any data is transferred, it is difficult to recover from the error on a seekable device and impossible on a non-seekable device. most new implementations support this behavior. the behavior required by POSIX.1โ2008 is to return the number of bytes transferred. okay so they picked a side and the side is "tell me how many bytes actually made it" ๐
POSIX.1โ2008 does not specify when an implementation that buffers read()s actually moves the data into the user-supplied buffer, so an implementation may choose to do this at the latest possible moment. therefore, an interrupt arriving earlier may not cause read() to return a partial byte count, but rather to return -1 and set errno to [EINTR]. sneaky little buffering situation going on there ๐
consideration was also given to combining the two previous options, and setting errno to [EINTR] while returning a short count. however, not only is there no existing practice that implements this, it is also contradictory to the idea that when errno is set, the function responsible shall return -1. so that idea got politely declined. it's giving "nice thought, doesn't work" โจ
this volume of POSIX.1โ2017 intentionally does not specify any pread() errors related to pipes, FIFOs, and sockets other than [ESPIPE]. that's the whole list. just the one. ๐
๐ฎ FUTURE DIRECTIONS ๐ฎ
None.
no future plans, bestie. living in the present. main character energy ๐ฆ
๐ SEE ALSO ๐
fcntl(), ioctl(), lseek(), open(), pipe(), readv()
The Base Definitions volume of POSIX.1โ2017, Chapter 11, General Terminal Interface, <stropts.h>, <sys_uio.h>, <unistd.h>
go read those if you want the full lore ๐
๐ COPYRIGHT ๐
portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. in the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. the original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. to report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
and that's the whole page, bestie ๐ this one came to you from IEEE/The Open Group, dated 2017, filed under READ(3P). go forth and read() responsibly, and remember: always check your return value ๐โจ๐
๐ฆ where this page comes from
- alpine 3.22: man-pages-posix 2017a-r0 ยท custom
- alpine 3.23: man-pages-posix 2017a-r0 ยท custom
- alpine 3.24: man-pages-posix 2017a-r0 ยท custom
- arch rolling: man-pages 6.19-1
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages-posix 2017a
- opensuse-leap 16.0: man-pages-posix 2017a-160000.4.1 ยท SUSE-IEEE
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms