1READ(3P) POSIX Programmer's Manual READ(3P)
2
3
4
6 This manual page is part of the POSIX Programmer's Manual. The Linux
7 implementation of this interface may differ (consult the corresponding
8 Linux manual page for details of Linux behavior), or the interface may
9 not be implemented on Linux.
10
12 pread, read — read from a file
13
15 #include <unistd.h>
16
17 ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
18 ssize_t read(int fildes, void *buf, size_t nbyte);
19
21 The read() function shall attempt to read nbyte bytes from the file
22 associated with the open file descriptor, fildes, into the buffer
23 pointed to by buf. The behavior of multiple concurrent reads on the
24 same pipe, FIFO, or terminal device is unspecified.
25
26 Before any action described below is taken, and if nbyte is zero, the
27 read() function may detect and return errors as described below. In the
28 absence of errors, or if error detection is not performed, the read()
29 function shall return zero and have no other results.
30
31 On files that support seeking (for example, a regular file), the read()
32 shall start at a position in the file given by the file offset associ‐
33 ated with fildes. The file offset shall be incremented by the number
34 of bytes actually read.
35
36 Files that do not support seeking—for example, terminals—always read
37 from the current position. The value of a file offset associated with
38 such a file is undefined.
39
40 No data transfer shall occur past the current end-of-file. If the
41 starting position is at or after the end-of-file, 0 shall be returned.
42 If the file refers to a device special file, the result of subsequent
43 read() requests is implementation-defined.
44
45 If the value of nbyte is greater than {SSIZE_MAX}, the result is imple‐
46 mentation-defined.
47
48 When attempting to read from an empty pipe or FIFO:
49
50 * If no process has the pipe open for writing, read() shall return 0
51 to indicate end-of-file.
52
53 * If some process has the pipe open for writing and O_NONBLOCK is
54 set, read() shall return -1 and set errno to [EAGAIN].
55
56 * If some process has the pipe open for writing and O_NONBLOCK is
57 clear, read() shall block the calling thread until some data is
58 written or the pipe is closed by all processes that had the pipe
59 open for writing.
60
61 When attempting to read a file (other than a pipe or FIFO) that sup‐
62 ports non-blocking reads and has no data currently available:
63
64 * If O_NONBLOCK is set, read() shall return -1 and set errno to
65 [EAGAIN].
66
67 * If O_NONBLOCK is clear, read() shall block the calling thread until
68 some data becomes available.
69
70 * The use of the O_NONBLOCK flag has no effect if there is some data
71 available.
72
73 The read() function reads data previously written to a file. If any
74 portion of a regular file prior to the end-of-file has not been writ‐
75 ten, read() shall return bytes with value 0. For example, lseek()
76 allows the file offset to be set beyond the end of existing data in the
77 file. If data is later written at this point, subsequent reads in the
78 gap between the previous end of data and the newly written data shall
79 return bytes with value 0 until data is written into the gap.
80
81 Upon successful completion, where nbyte is greater than 0, read() shall
82 mark for update the last data access timestamp of the file, and shall
83 return the number of bytes read. This number shall never be greater
84 than nbyte. The value returned may be less than nbyte if the number of
85 bytes left in the file is less than nbyte, if the read() request was
86 interrupted by a signal, or if the file is a pipe or FIFO or special
87 file and has fewer than nbyte bytes immediately available for reading.
88 For example, a read() from a file associated with a terminal may return
89 one typed line of data.
90
91 If a read() is interrupted by a signal before it reads any data, it
92 shall return -1 with errno set to [EINTR].
93
94 If a read() is interrupted by a signal after it has successfully read
95 some data, it shall return the number of bytes read.
96
97 For regular files, no data transfer shall occur past the offset maximum
98 established in the open file description associated with fildes.
99
100 If fildes refers to a socket, read() shall be equivalent to recv() with
101 no flags set.
102
103 If the O_DSYNC and O_RSYNC bits have been set, read I/O operations on
104 the file descriptor shall complete as defined by synchronized I/O data
105 integrity completion. If the O_SYNC and O_RSYNC bits have been set,
106 read I/O operations on the file descriptor shall complete as defined by
107 synchronized I/O file integrity completion.
108
109 If fildes refers to a shared memory object, the result of the read()
110 function is unspecified.
111
112 If fildes refers to a typed memory object, the result of the read()
113 function is unspecified.
114
115 A read() from a STREAMS file can read data in three different modes:
116 byte-stream mode, message-nondiscard mode, and message-discard mode.
117 The default shall be byte-stream mode. This can be changed using the
118 I_SRDOPT ioctl() request, and can be tested with I_GRDOPT ioctl(). In
119 byte-stream mode, read() shall retrieve data from the STREAM until as
120 many bytes as were requested are transferred, or until there is no more
121 data to be retrieved. Byte-stream mode ignores message boundaries.
122
123 In STREAMS message-nondiscard mode, read() shall retrieve data until as
124 many bytes as were requested are transferred, or until a message bound‐
125 ary is reached. If read() does not retrieve all the data in a message,
126 the remaining data shall be left on the STREAM, and can be retrieved by
127 the next read() call. Message-discard mode also retrieves data until as
128 many bytes as were requested are transferred, or a message boundary is
129 reached. However, unread data remaining in a message after the read()
130 returns shall be discarded, and shall not be available for a subsequent
131 read(), getmsg(), or getpmsg() call.
132
133 How read() handles zero-byte STREAMS messages is determined by the cur‐
134 rent read mode setting. In byte-stream mode, read() shall accept data
135 until it has read nbyte bytes, or until there is no more data to read,
136 or until a zero-byte message block is encountered. The read() function
137 shall then return the number of bytes read, and place the zero-byte
138 message back on the STREAM to be retrieved by the next read(),
139 getmsg(), or getpmsg(). In message-nondiscard mode or message-discard
140 mode, a zero-byte message shall return 0 and the message shall be
141 removed from the STREAM. When a zero-byte message is read as the first
142 message on a STREAM, the message shall be removed from the STREAM and 0
143 shall be returned, regardless of the read mode.
144
145 A read() from a STREAMS file shall return the data in the message at
146 the front of the STREAM head read queue, regardless of the priority
147 band of the message.
148
149 By default, STREAMs are in control-normal mode, in which a read() from
150 a STREAMS file can only process messages that contain a data part but
151 do not contain a control part. The read() shall fail if a message con‐
152 taining a control part is encountered at the STREAM head. This default
153 action can be changed by placing the STREAM in either control-data mode
154 or control-discard mode with the I_SRDOPT ioctl() command. In control-
155 data mode, read() shall convert any control part to data and pass it to
156 the application before passing any data part originally present in the
157 same message. In control-discard mode, read() shall discard message
158 control parts but return to the process any data part in the message.
159
160 In addition, read() shall fail if the STREAM head had processed an
161 asynchronous error before the call. In this case, the value of errno
162 shall not reflect the result of read(), but reflect the prior error. If
163 a hangup occurs on the STREAM being read, read() shall continue to
164 operate normally until the STREAM head read queue is empty. Thereafter,
165 it shall return 0.
166
167 The pread() function shall be equivalent to read(), except that it
168 shall read from a given position in the file without changing the file
169 offset. The first three arguments to pread() are the same as read()
170 with the addition of a fourth argument offset for the desired position
171 inside the file. An attempt to perform a pread() on a file that is
172 incapable of seeking shall result in an error.
173
175 Upon successful completion, these functions shall return a non-negative
176 integer indicating the number of bytes actually read. Otherwise, the
177 functions shall return -1 and set errno to indicate the error.
178
180 These functions shall fail if:
181
182 EAGAIN The file is neither a pipe, nor a FIFO, nor a socket, the O_NON‐
183 BLOCK flag is set for the file descriptor, and the thread would
184 be delayed in the read operation.
185
186 EBADF The fildes argument is not a valid file descriptor open for
187 reading.
188
189 EBADMSG
190 The file is a STREAM file that is set to control-normal mode and
191 the message waiting to be read includes a control part.
192
193 EINTR The read operation was terminated due to the receipt of a sig‐
194 nal, and no data was transferred.
195
196 EINVAL The STREAM or multiplexer referenced by fildes is linked
197 (directly or indirectly) downstream from a multiplexer.
198
199 EIO The process is a member of a background process group attempting
200 to read from its controlling terminal, and either the calling
201 thread is blocking SIGTTIN or the process is ignoring SIGTTIN or
202 the process group of the process is orphaned. This error may
203 also be generated for implementation-defined reasons.
204
205 EISDIR The fildes argument refers to a directory and the implementation
206 does not allow the directory to be read using read() or pread().
207 The readdir() function should be used instead.
208
209 EOVERFLOW
210 The file is a regular file, nbyte is greater than 0, the start‐
211 ing position is before the end-of-file, and the starting posi‐
212 tion is greater than or equal to the offset maximum established
213 in the open file description associated with fildes.
214
215 The pread() function shall fail if:
216
217 EINVAL The file is a regular file or block special file, and the offset
218 argument is negative. The file offset shall remain unchanged.
219
220 ESPIPE The file is incapable of seeking.
221
222 The read() function shall fail if:
223
224 EAGAIN The file is a pipe or FIFO, the O_NONBLOCK flag is set for the
225 file descriptor, and the thread would be delayed in the read
226 operation.
227
228 EAGAIN or EWOULDBLOCK
229 The file is a socket, the O_NONBLOCK flag is set for the file
230 descriptor, and the thread would be delayed in the read opera‐
231 tion.
232
233 ECONNRESET
234 A read was attempted on a socket and the connection was forcibly
235 closed by its peer.
236
237 ENOTCONN
238 A read was attempted on a socket that is not connected.
239
240 ETIMEDOUT
241 A read was attempted on a socket and a transmission timeout
242 occurred.
243
244 These functions may fail if:
245
246 EIO A physical I/O error has occurred.
247
248 ENOBUFS
249 Insufficient resources were available in the system to perform
250 the operation.
251
252 ENOMEM Insufficient memory was available to fulfill the request.
253
254 ENXIO A request was made of a nonexistent device, or the request was
255 outside the capabilities of the device.
256
257 The following sections are informative.
258
260 Reading Data into a Buffer
261 The following example reads data from the file associated with the file
262 descriptor fd into the buffer pointed to by buf.
263
264
265 #include <sys/types.h>
266 #include <unistd.h>
267 ...
268 char buf[20];
269 size_t nbytes;
270 ssize_t bytes_read;
271 int fd;
272 ...
273 nbytes = sizeof(buf);
274 bytes_read = read(fd, buf, nbytes);
275 ...
276
278 None.
279
281 This volume of POSIX.1‐2017 does not specify the value of the file off‐
282 set after an error is returned; there are too many cases. For program‐
283 ming errors, such as [EBADF], the concept is meaningless since no file
284 is involved. For errors that are detected immediately, such as
285 [EAGAIN], clearly the offset should not change. After an interrupt or
286 hardware error, however, an updated value would be very useful and is
287 the behavior of many implementations.
288
289 Note that a read() of zero bytes does not modify the last data access
290 timestamp. A read() that requests more than zero bytes, but returns
291 zero, is required to modify the last data access timestamp.
292
293 Implementations are allowed, but not required, to perform error check‐
294 ing for read() requests of zero bytes.
295
296 Input and Output
297 The use of I/O with large byte counts has always presented problems.
298 Ideas such as lread() and lwrite() (using and returning longs) were
299 considered at one time. The current solution is to use abstract types
300 on the ISO C standard function to read() and write(). The abstract
301 types can be declared so that existing functions work, but can also be
302 declared so that larger types can be represented in future implementa‐
303 tions. It is presumed that whatever constraints limit the maximum range
304 of size_t also limit portable I/O requests to the same range. This vol‐
305 ume of POSIX.1‐2017 also limits the range further by requiring that the
306 byte count be limited so that a signed return value remains meaningful.
307 Since the return type is also a (signed) abstract type, the byte count
308 can be defined by the implementation to be larger than an int can hold.
309
310 The standard developers considered adding atomicity requirements to a
311 pipe or FIFO, but recognized that due to the nature of pipes and FIFOs
312 there could be no guarantee of atomicity of reads of {PIPE_BUF} or any
313 other size that would be an aid to applications portability.
314
315 This volume of POSIX.1‐2017 requires that no action be taken for read()
316 or write() when nbyte is zero. This is not intended to take precedence
317 over detection of errors (such as invalid buffer pointers or file
318 descriptors). This is consistent with the rest of this volume of
319 POSIX.1‐2017, but the phrasing here could be misread to require detec‐
320 tion of the zero case before any other errors. A value of zero is to
321 be considered a correct value, for which the semantics are a no-op.
322
323 I/O is intended to be atomic to ordinary files and pipes and FIFOs.
324 Atomic means that all the bytes from a single operation that started
325 out together end up together, without interleaving from other I/O oper‐
326 ations. It is a known attribute of terminals that this is not honored,
327 and terminals are explicitly (and implicitly permanently) excepted,
328 making the behavior unspecified. The behavior for other device types is
329 also left unspecified, but the wording is intended to imply that future
330 standards might choose to specify atomicity (or not).
331
332 There were recommendations to add format parameters to read() and
333 write() in order to handle networked transfers among heterogeneous file
334 system and base hardware types. Such a facility may be required for
335 support by the OSI presentation of layer services. However, it was
336 determined that this should correspond with similar C-language facili‐
337 ties, and that is beyond the scope of this volume of POSIX.1‐2017. The
338 concept was suggested to the developers of the ISO C standard for their
339 consideration as a possible area for future work.
340
341 In 4.3 BSD, a read() or write() that is interrupted by a signal before
342 transferring any data does not by default return an [EINTR] error, but
343 is restarted. In 4.2 BSD, 4.3 BSD, and the Eighth Edition, there is an
344 additional function, select(), whose purpose is to pause until speci‐
345 fied activity (data to read, space to write, and so on) is detected on
346 specified file descriptors. It is common in applications written for
347 those systems for select() to be used before read() in situations (such
348 as keyboard input) where interruption of I/O due to a signal is
349 desired.
350
351 The issue of which files or file types are interruptible is considered
352 an implementation design issue. This is often affected primarily by
353 hardware and reliability issues.
354
355 There are no references to actions taken following an ``unrecoverable
356 error''. It is considered beyond the scope of this volume of
357 POSIX.1‐2017 to describe what happens in the case of hardware errors.
358
359 Earlier versions of this standard allowed two very different behaviors
360 with regard to the handling of interrupts. In order to minimize the
361 resulting confusion, it was decided that POSIX.1‐2008 should support
362 only one of these behaviors. Historical practice on AT&T-derived sys‐
363 tems was to have read() and write() return -1 and set errno to [EINTR]
364 when interrupted after some, but not all, of the data requested had
365 been transferred. However, the US Department of Commerce FIPS 151‐1 and
366 FIPS 151‐2 require the historical BSD behavior, in which read() and
367 write() return the number of bytes actually transferred before the
368 interrupt. If -1 is returned when any data is transferred, it is dif‐
369 ficult to recover from the error on a seekable device and impossible on
370 a non-seekable device. Most new implementations support this behavior.
371 The behavior required by POSIX.1‐2008 is to return the number of bytes
372 transferred.
373
374 POSIX.1‐2008 does not specify when an implementation that buffers
375 read()s actually moves the data into the user-supplied buffer, so an
376 implementation may choose to do this at the latest possible moment.
377 Therefore, an interrupt arriving earlier may not cause read() to return
378 a partial byte count, but rather to return -1 and set errno to [EINTR].
379
380 Consideration was also given to combining the two previous options, and
381 setting errno to [EINTR] while returning a short count. However, not
382 only is there no existing practice that implements this, it is also
383 contradictory to the idea that when errno is set, the function respon‐
384 sible shall return -1.
385
386 This volume of POSIX.1‐2017 intentionally does not specify any pread()
387 errors related to pipes, FIFOs, and sockets other than [ESPIPE].
388
390 None.
391
393 fcntl(), ioctl(), lseek(), open(), pipe(), readv()
394
395 The Base Definitions volume of POSIX.1‐2017, Chapter 11, General Termi‐
396 nal Interface, <stropts.h>, <sys_uio.h>, <unistd.h>
397
399 Portions of this text are reprinted and reproduced in electronic form
400 from IEEE Std 1003.1-2017, Standard for Information Technology -- Por‐
401 table Operating System Interface (POSIX), The Open Group Base Specifi‐
402 cations Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of
403 Electrical and Electronics Engineers, Inc and The Open Group. In the
404 event of any discrepancy between this version and the original IEEE and
405 The Open Group Standard, the original IEEE and The Open Group Standard
406 is the referee document. The original Standard can be obtained online
407 at http://www.opengroup.org/unix/online.html .
408
409 Any typographical or formatting errors that appear in this page are
410 most likely to have been introduced during the conversion of the source
411 files to man page format. To report such errors, see https://www.ker‐
412 nel.org/doc/man-pages/reporting_bugs.html .
413
414
415
416IEEE/The Open Group 2017 READ(3P)