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