]> git.ipfire.org Git - thirdparty/glibc.git/blob - manual/llio.texi
manual: Convert @tables of variables to @vtables.
[thirdparty/glibc.git] / manual / llio.texi
1 @node Low-Level I/O, File System Interface, I/O on Streams, Top
2 @c %MENU% Low-level, less portable I/O
3 @chapter Low-Level Input/Output
4
5 This chapter describes functions for performing low-level input/output
6 operations on file descriptors. These functions include the primitives
7 for the higher-level I/O functions described in @ref{I/O on Streams}, as
8 well as functions for performing low-level control operations for which
9 there are no equivalents on streams.
10
11 Stream-level I/O is more flexible and usually more convenient;
12 therefore, programmers generally use the descriptor-level functions only
13 when necessary. These are some of the usual reasons:
14
15 @itemize @bullet
16 @item
17 For reading binary files in large chunks.
18
19 @item
20 For reading an entire file into core before parsing it.
21
22 @item
23 To perform operations other than data transfer, which can only be done
24 with a descriptor. (You can use @code{fileno} to get the descriptor
25 corresponding to a stream.)
26
27 @item
28 To pass descriptors to a child process. (The child can create its own
29 stream to use a descriptor that it inherits, but cannot inherit a stream
30 directly.)
31 @end itemize
32
33 @menu
34 * Opening and Closing Files:: How to open and close file
35 descriptors.
36 * I/O Primitives:: Reading and writing data.
37 * File Position Primitive:: Setting a descriptor's file
38 position.
39 * Descriptors and Streams:: Converting descriptor to stream
40 or vice-versa.
41 * Stream/Descriptor Precautions:: Precautions needed if you use both
42 descriptors and streams.
43 * Scatter-Gather:: Fast I/O to discontinuous buffers.
44 * Memory-mapped I/O:: Using files like memory.
45 * Waiting for I/O:: How to check for input or output
46 on multiple file descriptors.
47 * Synchronizing I/O:: Making sure all I/O actions completed.
48 * Asynchronous I/O:: Perform I/O in parallel.
49 * Control Operations:: Various other operations on file
50 descriptors.
51 * Duplicating Descriptors:: Fcntl commands for duplicating
52 file descriptors.
53 * Descriptor Flags:: Fcntl commands for manipulating
54 flags associated with file
55 descriptors.
56 * File Status Flags:: Fcntl commands for manipulating
57 flags associated with open files.
58 * File Locks:: Fcntl commands for implementing
59 file locking.
60 * Open File Description Locks:: Fcntl commands for implementing
61 open file description locking.
62 * Open File Description Locks Example:: An example of open file description lock
63 usage
64 * Interrupt Input:: Getting an asynchronous signal when
65 input arrives.
66 * IOCTLs:: Generic I/O Control operations.
67 @end menu
68
69
70 @node Opening and Closing Files
71 @section Opening and Closing Files
72
73 @cindex opening a file descriptor
74 @cindex closing a file descriptor
75 This section describes the primitives for opening and closing files
76 using file descriptors. The @code{open} and @code{creat} functions are
77 declared in the header file @file{fcntl.h}, while @code{close} is
78 declared in @file{unistd.h}.
79 @pindex unistd.h
80 @pindex fcntl.h
81
82 @comment fcntl.h
83 @comment POSIX.1
84 @deftypefun int open (const char *@var{filename}, int @var{flags}[, mode_t @var{mode}])
85 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
86 The @code{open} function creates and returns a new file descriptor for
87 the file named by @var{filename}. Initially, the file position
88 indicator for the file is at the beginning of the file. The argument
89 @var{mode} (@pxref{Permission Bits}) is used only when a file is
90 created, but it doesn't hurt to supply the argument in any case.
91
92 The @var{flags} argument controls how the file is to be opened. This is
93 a bit mask; you create the value by the bitwise OR of the appropriate
94 parameters (using the @samp{|} operator in C).
95 @xref{File Status Flags}, for the parameters available.
96
97 The normal return value from @code{open} is a non-negative integer file
98 descriptor. In the case of an error, a value of @math{-1} is returned
99 instead. In addition to the usual file name errors (@pxref{File
100 Name Errors}), the following @code{errno} error conditions are defined
101 for this function:
102
103 @table @code
104 @item EACCES
105 The file exists but is not readable/writable as requested by the @var{flags}
106 argument, or the file does not exist and the directory is unwritable so
107 it cannot be created.
108
109 @item EEXIST
110 Both @code{O_CREAT} and @code{O_EXCL} are set, and the named file already
111 exists.
112
113 @item EINTR
114 The @code{open} operation was interrupted by a signal.
115 @xref{Interrupted Primitives}.
116
117 @item EISDIR
118 The @var{flags} argument specified write access, and the file is a directory.
119
120 @item EMFILE
121 The process has too many files open.
122 The maximum number of file descriptors is controlled by the
123 @code{RLIMIT_NOFILE} resource limit; @pxref{Limits on Resources}.
124
125 @item ENFILE
126 The entire system, or perhaps the file system which contains the
127 directory, cannot support any additional open files at the moment.
128 (This problem cannot happen on @gnuhurdsystems{}.)
129
130 @item ENOENT
131 The named file does not exist, and @code{O_CREAT} is not specified.
132
133 @item ENOSPC
134 The directory or file system that would contain the new file cannot be
135 extended, because there is no disk space left.
136
137 @item ENXIO
138 @code{O_NONBLOCK} and @code{O_WRONLY} are both set in the @var{flags}
139 argument, the file named by @var{filename} is a FIFO (@pxref{Pipes and
140 FIFOs}), and no process has the file open for reading.
141
142 @item EROFS
143 The file resides on a read-only file system and any of @w{@code{O_WRONLY}},
144 @code{O_RDWR}, and @code{O_TRUNC} are set in the @var{flags} argument,
145 or @code{O_CREAT} is set and the file does not already exist.
146 @end table
147
148 @c !!! umask
149
150 If on a 32 bit machine the sources are translated with
151 @code{_FILE_OFFSET_BITS == 64} the function @code{open} returns a file
152 descriptor opened in the large file mode which enables the file handling
153 functions to use files up to @twoexp{63} bytes in size and offset from
154 @minus{}@twoexp{63} to @twoexp{63}. This happens transparently for the user
155 since all of the low-level file handling functions are equally replaced.
156
157 This function is a cancellation point in multi-threaded programs. This
158 is a problem if the thread allocates some resources (like memory, file
159 descriptors, semaphores or whatever) at the time @code{open} is
160 called. If the thread gets canceled these resources stay allocated
161 until the program ends. To avoid this calls to @code{open} should be
162 protected using cancellation handlers.
163 @c ref pthread_cleanup_push / pthread_cleanup_pop
164
165 The @code{open} function is the underlying primitive for the @code{fopen}
166 and @code{freopen} functions, that create streams.
167 @end deftypefun
168
169 @comment fcntl.h
170 @comment Unix98
171 @deftypefun int open64 (const char *@var{filename}, int @var{flags}[, mode_t @var{mode}])
172 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
173 This function is similar to @code{open}. It returns a file descriptor
174 which can be used to access the file named by @var{filename}. The only
175 difference is that on 32 bit systems the file is opened in the
176 large file mode. I.e., file length and file offsets can exceed 31 bits.
177
178 When the sources are translated with @code{_FILE_OFFSET_BITS == 64} this
179 function is actually available under the name @code{open}. I.e., the
180 new, extended API using 64 bit file sizes and offsets transparently
181 replaces the old API.
182 @end deftypefun
183
184 @comment fcntl.h
185 @comment POSIX.1
186 @deftypefn {Obsolete function} int creat (const char *@var{filename}, mode_t @var{mode})
187 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
188 This function is obsolete. The call:
189
190 @smallexample
191 creat (@var{filename}, @var{mode})
192 @end smallexample
193
194 @noindent
195 is equivalent to:
196
197 @smallexample
198 open (@var{filename}, O_WRONLY | O_CREAT | O_TRUNC, @var{mode})
199 @end smallexample
200
201 If on a 32 bit machine the sources are translated with
202 @code{_FILE_OFFSET_BITS == 64} the function @code{creat} returns a file
203 descriptor opened in the large file mode which enables the file handling
204 functions to use files up to @twoexp{63} in size and offset from
205 @minus{}@twoexp{63} to @twoexp{63}. This happens transparently for the user
206 since all of the low-level file handling functions are equally replaced.
207 @end deftypefn
208
209 @comment fcntl.h
210 @comment Unix98
211 @deftypefn {Obsolete function} int creat64 (const char *@var{filename}, mode_t @var{mode})
212 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
213 This function is similar to @code{creat}. It returns a file descriptor
214 which can be used to access the file named by @var{filename}. The only
215 difference is that on 32 bit systems the file is opened in the
216 large file mode. I.e., file length and file offsets can exceed 31 bits.
217
218 To use this file descriptor one must not use the normal operations but
219 instead the counterparts named @code{*64}, e.g., @code{read64}.
220
221 When the sources are translated with @code{_FILE_OFFSET_BITS == 64} this
222 function is actually available under the name @code{open}. I.e., the
223 new, extended API using 64 bit file sizes and offsets transparently
224 replaces the old API.
225 @end deftypefn
226
227 @comment unistd.h
228 @comment POSIX.1
229 @deftypefun int close (int @var{filedes})
230 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
231 The function @code{close} closes the file descriptor @var{filedes}.
232 Closing a file has the following consequences:
233
234 @itemize @bullet
235 @item
236 The file descriptor is deallocated.
237
238 @item
239 Any record locks owned by the process on the file are unlocked.
240
241 @item
242 When all file descriptors associated with a pipe or FIFO have been closed,
243 any unread data is discarded.
244 @end itemize
245
246 This function is a cancellation point in multi-threaded programs. This
247 is a problem if the thread allocates some resources (like memory, file
248 descriptors, semaphores or whatever) at the time @code{close} is
249 called. If the thread gets canceled these resources stay allocated
250 until the program ends. To avoid this, calls to @code{close} should be
251 protected using cancellation handlers.
252 @c ref pthread_cleanup_push / pthread_cleanup_pop
253
254 The normal return value from @code{close} is @math{0}; a value of @math{-1}
255 is returned in case of failure. The following @code{errno} error
256 conditions are defined for this function:
257
258 @table @code
259 @item EBADF
260 The @var{filedes} argument is not a valid file descriptor.
261
262 @item EINTR
263 The @code{close} call was interrupted by a signal.
264 @xref{Interrupted Primitives}.
265 Here is an example of how to handle @code{EINTR} properly:
266
267 @smallexample
268 TEMP_FAILURE_RETRY (close (desc));
269 @end smallexample
270
271 @item ENOSPC
272 @itemx EIO
273 @itemx EDQUOT
274 When the file is accessed by NFS, these errors from @code{write} can sometimes
275 not be detected until @code{close}. @xref{I/O Primitives}, for details
276 on their meaning.
277 @end table
278
279 Please note that there is @emph{no} separate @code{close64} function.
280 This is not necessary since this function does not determine nor depend
281 on the mode of the file. The kernel which performs the @code{close}
282 operation knows which mode the descriptor is used for and can handle
283 this situation.
284 @end deftypefun
285
286 To close a stream, call @code{fclose} (@pxref{Closing Streams}) instead
287 of trying to close its underlying file descriptor with @code{close}.
288 This flushes any buffered output and updates the stream object to
289 indicate that it is closed.
290
291 @node I/O Primitives
292 @section Input and Output Primitives
293
294 This section describes the functions for performing primitive input and
295 output operations on file descriptors: @code{read}, @code{write}, and
296 @code{lseek}. These functions are declared in the header file
297 @file{unistd.h}.
298 @pindex unistd.h
299
300 @comment unistd.h
301 @comment POSIX.1
302 @deftp {Data Type} ssize_t
303 This data type is used to represent the sizes of blocks that can be
304 read or written in a single operation. It is similar to @code{size_t},
305 but must be a signed type.
306 @end deftp
307
308 @cindex reading from a file descriptor
309 @comment unistd.h
310 @comment POSIX.1
311 @deftypefun ssize_t read (int @var{filedes}, void *@var{buffer}, size_t @var{size})
312 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
313 The @code{read} function reads up to @var{size} bytes from the file
314 with descriptor @var{filedes}, storing the results in the @var{buffer}.
315 (This is not necessarily a character string, and no terminating null
316 character is added.)
317
318 @cindex end-of-file, on a file descriptor
319 The return value is the number of bytes actually read. This might be
320 less than @var{size}; for example, if there aren't that many bytes left
321 in the file or if there aren't that many bytes immediately available.
322 The exact behavior depends on what kind of file it is. Note that
323 reading less than @var{size} bytes is not an error.
324
325 A value of zero indicates end-of-file (except if the value of the
326 @var{size} argument is also zero). This is not considered an error.
327 If you keep calling @code{read} while at end-of-file, it will keep
328 returning zero and doing nothing else.
329
330 If @code{read} returns at least one character, there is no way you can
331 tell whether end-of-file was reached. But if you did reach the end, the
332 next read will return zero.
333
334 In case of an error, @code{read} returns @math{-1}. The following
335 @code{errno} error conditions are defined for this function:
336
337 @table @code
338 @item EAGAIN
339 Normally, when no input is immediately available, @code{read} waits for
340 some input. But if the @code{O_NONBLOCK} flag is set for the file
341 (@pxref{File Status Flags}), @code{read} returns immediately without
342 reading any data, and reports this error.
343
344 @strong{Compatibility Note:} Most versions of BSD Unix use a different
345 error code for this: @code{EWOULDBLOCK}. In @theglibc{},
346 @code{EWOULDBLOCK} is an alias for @code{EAGAIN}, so it doesn't matter
347 which name you use.
348
349 On some systems, reading a large amount of data from a character special
350 file can also fail with @code{EAGAIN} if the kernel cannot find enough
351 physical memory to lock down the user's pages. This is limited to
352 devices that transfer with direct memory access into the user's memory,
353 which means it does not include terminals, since they always use
354 separate buffers inside the kernel. This problem never happens on
355 @gnuhurdsystems{}.
356
357 Any condition that could result in @code{EAGAIN} can instead result in a
358 successful @code{read} which returns fewer bytes than requested.
359 Calling @code{read} again immediately would result in @code{EAGAIN}.
360
361 @item EBADF
362 The @var{filedes} argument is not a valid file descriptor,
363 or is not open for reading.
364
365 @item EINTR
366 @code{read} was interrupted by a signal while it was waiting for input.
367 @xref{Interrupted Primitives}. A signal will not necessarily cause
368 @code{read} to return @code{EINTR}; it may instead result in a
369 successful @code{read} which returns fewer bytes than requested.
370
371 @item EIO
372 For many devices, and for disk files, this error code indicates
373 a hardware error.
374
375 @code{EIO} also occurs when a background process tries to read from the
376 controlling terminal, and the normal action of stopping the process by
377 sending it a @code{SIGTTIN} signal isn't working. This might happen if
378 the signal is being blocked or ignored, or because the process group is
379 orphaned. @xref{Job Control}, for more information about job control,
380 and @ref{Signal Handling}, for information about signals.
381
382 @item EINVAL
383 In some systems, when reading from a character or block device, position
384 and size offsets must be aligned to a particular block size. This error
385 indicates that the offsets were not properly aligned.
386 @end table
387
388 Please note that there is no function named @code{read64}. This is not
389 necessary since this function does not directly modify or handle the
390 possibly wide file offset. Since the kernel handles this state
391 internally, the @code{read} function can be used for all cases.
392
393 This function is a cancellation point in multi-threaded programs. This
394 is a problem if the thread allocates some resources (like memory, file
395 descriptors, semaphores or whatever) at the time @code{read} is
396 called. If the thread gets canceled these resources stay allocated
397 until the program ends. To avoid this, calls to @code{read} should be
398 protected using cancellation handlers.
399 @c ref pthread_cleanup_push / pthread_cleanup_pop
400
401 The @code{read} function is the underlying primitive for all of the
402 functions that read from streams, such as @code{fgetc}.
403 @end deftypefun
404
405 @comment unistd.h
406 @comment Unix98
407 @deftypefun ssize_t pread (int @var{filedes}, void *@var{buffer}, size_t @var{size}, off_t @var{offset})
408 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
409 @c This is usually a safe syscall. The sysdeps/posix fallback emulation
410 @c is not MT-Safe because it uses lseek, read and lseek back, but is it
411 @c used anywhere?
412 The @code{pread} function is similar to the @code{read} function. The
413 first three arguments are identical, and the return values and error
414 codes also correspond.
415
416 The difference is the fourth argument and its handling. The data block
417 is not read from the current position of the file descriptor
418 @code{filedes}. Instead the data is read from the file starting at
419 position @var{offset}. The position of the file descriptor itself is
420 not affected by the operation. The value is the same as before the call.
421
422 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
423 @code{pread} function is in fact @code{pread64} and the type
424 @code{off_t} has 64 bits, which makes it possible to handle files up to
425 @twoexp{63} bytes in length.
426
427 The return value of @code{pread} describes the number of bytes read.
428 In the error case it returns @math{-1} like @code{read} does and the
429 error codes are also the same, with these additions:
430
431 @table @code
432 @item EINVAL
433 The value given for @var{offset} is negative and therefore illegal.
434
435 @item ESPIPE
436 The file descriptor @var{filedes} is associated with a pipe or a FIFO and
437 this device does not allow positioning of the file pointer.
438 @end table
439
440 The function is an extension defined in the Unix Single Specification
441 version 2.
442 @end deftypefun
443
444 @comment unistd.h
445 @comment Unix98
446 @deftypefun ssize_t pread64 (int @var{filedes}, void *@var{buffer}, size_t @var{size}, off64_t @var{offset})
447 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
448 @c This is usually a safe syscall. The sysdeps/posix fallback emulation
449 @c is not MT-Safe because it uses lseek64, read and lseek64 back, but is
450 @c it used anywhere?
451 This function is similar to the @code{pread} function. The difference
452 is that the @var{offset} parameter is of type @code{off64_t} instead of
453 @code{off_t} which makes it possible on 32 bit machines to address
454 files larger than @twoexp{31} bytes and up to @twoexp{63} bytes. The
455 file descriptor @code{filedes} must be opened using @code{open64} since
456 otherwise the large offsets possible with @code{off64_t} will lead to
457 errors with a descriptor in small file mode.
458
459 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
460 32 bit machine this function is actually available under the name
461 @code{pread} and so transparently replaces the 32 bit interface.
462 @end deftypefun
463
464 @cindex writing to a file descriptor
465 @comment unistd.h
466 @comment POSIX.1
467 @deftypefun ssize_t write (int @var{filedes}, const void *@var{buffer}, size_t @var{size})
468 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
469 @c Some say write is thread-unsafe on Linux without O_APPEND. In the VFS layer
470 @c the vfs_write() does no locking around the acquisition of a file offset and
471 @c therefore multiple threads / kernel tasks may race and get the same offset
472 @c resulting in data loss.
473 @c
474 @c See:
475 @c http://thread.gmane.org/gmane.linux.kernel/397980
476 @c http://lwn.net/Articles/180387/
477 @c
478 @c The counter argument is that POSIX only says that the write starts at the
479 @c file position and that the file position is updated *before* the function
480 @c returns. What that really means is that any expectation of atomic writes is
481 @c strictly an invention of the interpretation of the reader. Data loss could
482 @c happen if two threads start the write at the same time. Only writes that
483 @c come after the return of another write are guaranteed to follow the other
484 @c write.
485 @c
486 @c The other side of the coin is that POSIX goes on further to say in
487 @c "2.9.7 Thread Interactions with Regular File Operations" that threads
488 @c should never see interleaving sets of file operations, but it is insane
489 @c to do anything like that because it kills performance, so you don't get
490 @c those guarantees in Linux.
491 @c
492 @c So we mark it thread safe, it doesn't blow up, but you might loose
493 @c data, and we don't strictly meet the POSIX requirements.
494 @c
495 @c The fix for file offsets racing was merged in 3.14, the commits were:
496 @c 9c225f2655e36a470c4f58dbbc99244c5fc7f2d4, and
497 @c d7a15f8d0777955986a2ab00ab181795cab14b01. Therefore after Linux 3.14 you
498 @c should get mostly MT-safe writes.
499 The @code{write} function writes up to @var{size} bytes from
500 @var{buffer} to the file with descriptor @var{filedes}. The data in
501 @var{buffer} is not necessarily a character string and a null character is
502 output like any other character.
503
504 The return value is the number of bytes actually written. This may be
505 @var{size}, but can always be smaller. Your program should always call
506 @code{write} in a loop, iterating until all the data is written.
507
508 Once @code{write} returns, the data is enqueued to be written and can be
509 read back right away, but it is not necessarily written out to permanent
510 storage immediately. You can use @code{fsync} when you need to be sure
511 your data has been permanently stored before continuing. (It is more
512 efficient for the system to batch up consecutive writes and do them all
513 at once when convenient. Normally they will always be written to disk
514 within a minute or less.) Modern systems provide another function
515 @code{fdatasync} which guarantees integrity only for the file data and
516 is therefore faster.
517 @c !!! xref fsync, fdatasync
518 You can use the @code{O_FSYNC} open mode to make @code{write} always
519 store the data to disk before returning; @pxref{Operating Modes}.
520
521 In the case of an error, @code{write} returns @math{-1}. The following
522 @code{errno} error conditions are defined for this function:
523
524 @table @code
525 @item EAGAIN
526 Normally, @code{write} blocks until the write operation is complete.
527 But if the @code{O_NONBLOCK} flag is set for the file (@pxref{Control
528 Operations}), it returns immediately without writing any data and
529 reports this error. An example of a situation that might cause the
530 process to block on output is writing to a terminal device that supports
531 flow control, where output has been suspended by receipt of a STOP
532 character.
533
534 @strong{Compatibility Note:} Most versions of BSD Unix use a different
535 error code for this: @code{EWOULDBLOCK}. In @theglibc{},
536 @code{EWOULDBLOCK} is an alias for @code{EAGAIN}, so it doesn't matter
537 which name you use.
538
539 On some systems, writing a large amount of data from a character special
540 file can also fail with @code{EAGAIN} if the kernel cannot find enough
541 physical memory to lock down the user's pages. This is limited to
542 devices that transfer with direct memory access into the user's memory,
543 which means it does not include terminals, since they always use
544 separate buffers inside the kernel. This problem does not arise on
545 @gnuhurdsystems{}.
546
547 @item EBADF
548 The @var{filedes} argument is not a valid file descriptor,
549 or is not open for writing.
550
551 @item EFBIG
552 The size of the file would become larger than the implementation can support.
553
554 @item EINTR
555 The @code{write} operation was interrupted by a signal while it was
556 blocked waiting for completion. A signal will not necessarily cause
557 @code{write} to return @code{EINTR}; it may instead result in a
558 successful @code{write} which writes fewer bytes than requested.
559 @xref{Interrupted Primitives}.
560
561 @item EIO
562 For many devices, and for disk files, this error code indicates
563 a hardware error.
564
565 @item ENOSPC
566 The device containing the file is full.
567
568 @item EPIPE
569 This error is returned when you try to write to a pipe or FIFO that
570 isn't open for reading by any process. When this happens, a @code{SIGPIPE}
571 signal is also sent to the process; see @ref{Signal Handling}.
572
573 @item EINVAL
574 In some systems, when writing to a character or block device, position
575 and size offsets must be aligned to a particular block size. This error
576 indicates that the offsets were not properly aligned.
577 @end table
578
579 Unless you have arranged to prevent @code{EINTR} failures, you should
580 check @code{errno} after each failing call to @code{write}, and if the
581 error was @code{EINTR}, you should simply repeat the call.
582 @xref{Interrupted Primitives}. The easy way to do this is with the
583 macro @code{TEMP_FAILURE_RETRY}, as follows:
584
585 @smallexample
586 nbytes = TEMP_FAILURE_RETRY (write (desc, buffer, count));
587 @end smallexample
588
589 Please note that there is no function named @code{write64}. This is not
590 necessary since this function does not directly modify or handle the
591 possibly wide file offset. Since the kernel handles this state
592 internally the @code{write} function can be used for all cases.
593
594 This function is a cancellation point in multi-threaded programs. This
595 is a problem if the thread allocates some resources (like memory, file
596 descriptors, semaphores or whatever) at the time @code{write} is
597 called. If the thread gets canceled these resources stay allocated
598 until the program ends. To avoid this, calls to @code{write} should be
599 protected using cancellation handlers.
600 @c ref pthread_cleanup_push / pthread_cleanup_pop
601
602 The @code{write} function is the underlying primitive for all of the
603 functions that write to streams, such as @code{fputc}.
604 @end deftypefun
605
606 @comment unistd.h
607 @comment Unix98
608 @deftypefun ssize_t pwrite (int @var{filedes}, const void *@var{buffer}, size_t @var{size}, off_t @var{offset})
609 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
610 @c This is usually a safe syscall. The sysdeps/posix fallback emulation
611 @c is not MT-Safe because it uses lseek, write and lseek back, but is it
612 @c used anywhere?
613 The @code{pwrite} function is similar to the @code{write} function. The
614 first three arguments are identical, and the return values and error codes
615 also correspond.
616
617 The difference is the fourth argument and its handling. The data block
618 is not written to the current position of the file descriptor
619 @code{filedes}. Instead the data is written to the file starting at
620 position @var{offset}. The position of the file descriptor itself is
621 not affected by the operation. The value is the same as before the call.
622
623 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
624 @code{pwrite} function is in fact @code{pwrite64} and the type
625 @code{off_t} has 64 bits, which makes it possible to handle files up to
626 @twoexp{63} bytes in length.
627
628 The return value of @code{pwrite} describes the number of written bytes.
629 In the error case it returns @math{-1} like @code{write} does and the
630 error codes are also the same, with these additions:
631
632 @table @code
633 @item EINVAL
634 The value given for @var{offset} is negative and therefore illegal.
635
636 @item ESPIPE
637 The file descriptor @var{filedes} is associated with a pipe or a FIFO and
638 this device does not allow positioning of the file pointer.
639 @end table
640
641 The function is an extension defined in the Unix Single Specification
642 version 2.
643 @end deftypefun
644
645 @comment unistd.h
646 @comment Unix98
647 @deftypefun ssize_t pwrite64 (int @var{filedes}, const void *@var{buffer}, size_t @var{size}, off64_t @var{offset})
648 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
649 @c This is usually a safe syscall. The sysdeps/posix fallback emulation
650 @c is not MT-Safe because it uses lseek64, write and lseek64 back, but
651 @c is it used anywhere?
652 This function is similar to the @code{pwrite} function. The difference
653 is that the @var{offset} parameter is of type @code{off64_t} instead of
654 @code{off_t} which makes it possible on 32 bit machines to address
655 files larger than @twoexp{31} bytes and up to @twoexp{63} bytes. The
656 file descriptor @code{filedes} must be opened using @code{open64} since
657 otherwise the large offsets possible with @code{off64_t} will lead to
658 errors with a descriptor in small file mode.
659
660 When the source file is compiled using @code{_FILE_OFFSET_BITS == 64} on a
661 32 bit machine this function is actually available under the name
662 @code{pwrite} and so transparently replaces the 32 bit interface.
663 @end deftypefun
664
665
666 @node File Position Primitive
667 @section Setting the File Position of a Descriptor
668
669 Just as you can set the file position of a stream with @code{fseek}, you
670 can set the file position of a descriptor with @code{lseek}. This
671 specifies the position in the file for the next @code{read} or
672 @code{write} operation. @xref{File Positioning}, for more information
673 on the file position and what it means.
674
675 To read the current file position value from a descriptor, use
676 @code{lseek (@var{desc}, 0, SEEK_CUR)}.
677
678 @cindex file positioning on a file descriptor
679 @cindex positioning a file descriptor
680 @cindex seeking on a file descriptor
681 @comment unistd.h
682 @comment POSIX.1
683 @deftypefun off_t lseek (int @var{filedes}, off_t @var{offset}, int @var{whence})
684 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
685 The @code{lseek} function is used to change the file position of the
686 file with descriptor @var{filedes}.
687
688 The @var{whence} argument specifies how the @var{offset} should be
689 interpreted, in the same way as for the @code{fseek} function, and it must
690 be one of the symbolic constants @code{SEEK_SET}, @code{SEEK_CUR}, or
691 @code{SEEK_END}.
692
693 @vtable @code
694 @item SEEK_SET
695 Specifies that @var{offset} is a count of characters from the beginning
696 of the file.
697
698 @item SEEK_CUR
699 Specifies that @var{offset} is a count of characters from the current
700 file position. This count may be positive or negative.
701
702 @item SEEK_END
703 Specifies that @var{offset} is a count of characters from the end of
704 the file. A negative count specifies a position within the current
705 extent of the file; a positive count specifies a position past the
706 current end. If you set the position past the current end, and
707 actually write data, you will extend the file with zeros up to that
708 position.
709 @end vtable
710
711 The return value from @code{lseek} is normally the resulting file
712 position, measured in bytes from the beginning of the file.
713 You can use this feature together with @code{SEEK_CUR} to read the
714 current file position.
715
716 If you want to append to the file, setting the file position to the
717 current end of file with @code{SEEK_END} is not sufficient. Another
718 process may write more data after you seek but before you write,
719 extending the file so the position you write onto clobbers their data.
720 Instead, use the @code{O_APPEND} operating mode; @pxref{Operating Modes}.
721
722 You can set the file position past the current end of the file. This
723 does not by itself make the file longer; @code{lseek} never changes the
724 file. But subsequent output at that position will extend the file.
725 Characters between the previous end of file and the new position are
726 filled with zeros. Extending the file in this way can create a
727 ``hole'': the blocks of zeros are not actually allocated on disk, so the
728 file takes up less space than it appears to; it is then called a
729 ``sparse file''.
730 @cindex sparse files
731 @cindex holes in files
732
733 If the file position cannot be changed, or the operation is in some way
734 invalid, @code{lseek} returns a value of @math{-1}. The following
735 @code{errno} error conditions are defined for this function:
736
737 @table @code
738 @item EBADF
739 The @var{filedes} is not a valid file descriptor.
740
741 @item EINVAL
742 The @var{whence} argument value is not valid, or the resulting
743 file offset is not valid. A file offset is invalid.
744
745 @item ESPIPE
746 The @var{filedes} corresponds to an object that cannot be positioned,
747 such as a pipe, FIFO or terminal device. (POSIX.1 specifies this error
748 only for pipes and FIFOs, but on @gnusystems{}, you always get
749 @code{ESPIPE} if the object is not seekable.)
750 @end table
751
752 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
753 @code{lseek} function is in fact @code{lseek64} and the type
754 @code{off_t} has 64 bits which makes it possible to handle files up to
755 @twoexp{63} bytes in length.
756
757 This function is a cancellation point in multi-threaded programs. This
758 is a problem if the thread allocates some resources (like memory, file
759 descriptors, semaphores or whatever) at the time @code{lseek} is
760 called. If the thread gets canceled these resources stay allocated
761 until the program ends. To avoid this calls to @code{lseek} should be
762 protected using cancellation handlers.
763 @c ref pthread_cleanup_push / pthread_cleanup_pop
764
765 The @code{lseek} function is the underlying primitive for the
766 @code{fseek}, @code{fseeko}, @code{ftell}, @code{ftello} and
767 @code{rewind} functions, which operate on streams instead of file
768 descriptors.
769 @end deftypefun
770
771 @comment unistd.h
772 @comment Unix98
773 @deftypefun off64_t lseek64 (int @var{filedes}, off64_t @var{offset}, int @var{whence})
774 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
775 This function is similar to the @code{lseek} function. The difference
776 is that the @var{offset} parameter is of type @code{off64_t} instead of
777 @code{off_t} which makes it possible on 32 bit machines to address
778 files larger than @twoexp{31} bytes and up to @twoexp{63} bytes. The
779 file descriptor @code{filedes} must be opened using @code{open64} since
780 otherwise the large offsets possible with @code{off64_t} will lead to
781 errors with a descriptor in small file mode.
782
783 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
784 32 bits machine this function is actually available under the name
785 @code{lseek} and so transparently replaces the 32 bit interface.
786 @end deftypefun
787
788 You can have multiple descriptors for the same file if you open the file
789 more than once, or if you duplicate a descriptor with @code{dup}.
790 Descriptors that come from separate calls to @code{open} have independent
791 file positions; using @code{lseek} on one descriptor has no effect on the
792 other. For example,
793
794 @smallexample
795 @group
796 @{
797 int d1, d2;
798 char buf[4];
799 d1 = open ("foo", O_RDONLY);
800 d2 = open ("foo", O_RDONLY);
801 lseek (d1, 1024, SEEK_SET);
802 read (d2, buf, 4);
803 @}
804 @end group
805 @end smallexample
806
807 @noindent
808 will read the first four characters of the file @file{foo}. (The
809 error-checking code necessary for a real program has been omitted here
810 for brevity.)
811
812 By contrast, descriptors made by duplication share a common file
813 position with the original descriptor that was duplicated. Anything
814 which alters the file position of one of the duplicates, including
815 reading or writing data, affects all of them alike. Thus, for example,
816
817 @smallexample
818 @{
819 int d1, d2, d3;
820 char buf1[4], buf2[4];
821 d1 = open ("foo", O_RDONLY);
822 d2 = dup (d1);
823 d3 = dup (d2);
824 lseek (d3, 1024, SEEK_SET);
825 read (d1, buf1, 4);
826 read (d2, buf2, 4);
827 @}
828 @end smallexample
829
830 @noindent
831 will read four characters starting with the 1024'th character of
832 @file{foo}, and then four more characters starting with the 1028'th
833 character.
834
835 @comment sys/types.h
836 @comment POSIX.1
837 @deftp {Data Type} off_t
838 This is a signed integer type used to represent file sizes. In
839 @theglibc{}, this type is no narrower than @code{int}.
840
841 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
842 is transparently replaced by @code{off64_t}.
843 @end deftp
844
845 @comment sys/types.h
846 @comment Unix98
847 @deftp {Data Type} off64_t
848 This type is used similar to @code{off_t}. The difference is that even
849 on 32 bit machines, where the @code{off_t} type would have 32 bits,
850 @code{off64_t} has 64 bits and so is able to address files up to
851 @twoexp{63} bytes in length.
852
853 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
854 available under the name @code{off_t}.
855 @end deftp
856
857 These aliases for the @samp{SEEK_@dots{}} constants exist for the sake
858 of compatibility with older BSD systems. They are defined in two
859 different header files: @file{fcntl.h} and @file{sys/file.h}.
860
861 @vtable @code
862 @item L_SET
863 An alias for @code{SEEK_SET}.
864
865 @item L_INCR
866 An alias for @code{SEEK_CUR}.
867
868 @item L_XTND
869 An alias for @code{SEEK_END}.
870 @end vtable
871
872 @node Descriptors and Streams
873 @section Descriptors and Streams
874 @cindex streams, and file descriptors
875 @cindex converting file descriptor to stream
876 @cindex extracting file descriptor from stream
877
878 Given an open file descriptor, you can create a stream for it with the
879 @code{fdopen} function. You can get the underlying file descriptor for
880 an existing stream with the @code{fileno} function. These functions are
881 declared in the header file @file{stdio.h}.
882 @pindex stdio.h
883
884 @comment stdio.h
885 @comment POSIX.1
886 @deftypefun {FILE *} fdopen (int @var{filedes}, const char *@var{opentype})
887 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @aculock{}}}
888 The @code{fdopen} function returns a new stream for the file descriptor
889 @var{filedes}.
890
891 The @var{opentype} argument is interpreted in the same way as for the
892 @code{fopen} function (@pxref{Opening Streams}), except that
893 the @samp{b} option is not permitted; this is because @gnusystems{} make no
894 distinction between text and binary files. Also, @code{"w"} and
895 @code{"w+"} do not cause truncation of the file; these have an effect only
896 when opening a file, and in this case the file has already been opened.
897 You must make sure that the @var{opentype} argument matches the actual
898 mode of the open file descriptor.
899
900 The return value is the new stream. If the stream cannot be created
901 (for example, if the modes for the file indicated by the file descriptor
902 do not permit the access specified by the @var{opentype} argument), a
903 null pointer is returned instead.
904
905 In some other systems, @code{fdopen} may fail to detect that the modes
906 for file descriptors do not permit the access specified by
907 @code{opentype}. @Theglibc{} always checks for this.
908 @end deftypefun
909
910 For an example showing the use of the @code{fdopen} function,
911 see @ref{Creating a Pipe}.
912
913 @comment stdio.h
914 @comment POSIX.1
915 @deftypefun int fileno (FILE *@var{stream})
916 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
917 This function returns the file descriptor associated with the stream
918 @var{stream}. If an error is detected (for example, if the @var{stream}
919 is not valid) or if @var{stream} does not do I/O to a file,
920 @code{fileno} returns @math{-1}.
921 @end deftypefun
922
923 @comment stdio.h
924 @comment GNU
925 @deftypefun int fileno_unlocked (FILE *@var{stream})
926 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
927 The @code{fileno_unlocked} function is equivalent to the @code{fileno}
928 function except that it does not implicitly lock the stream if the state
929 is @code{FSETLOCKING_INTERNAL}.
930
931 This function is a GNU extension.
932 @end deftypefun
933
934 @cindex standard file descriptors
935 @cindex file descriptors, standard
936 There are also symbolic constants defined in @file{unistd.h} for the
937 file descriptors belonging to the standard streams @code{stdin},
938 @code{stdout}, and @code{stderr}; see @ref{Standard Streams}.
939 @pindex unistd.h
940
941 @vtable @code
942 @comment unistd.h
943 @comment POSIX.1
944 @item STDIN_FILENO
945 This macro has value @code{0}, which is the file descriptor for
946 standard input.
947 @cindex standard input file descriptor
948
949 @comment unistd.h
950 @comment POSIX.1
951 @item STDOUT_FILENO
952 This macro has value @code{1}, which is the file descriptor for
953 standard output.
954 @cindex standard output file descriptor
955
956 @comment unistd.h
957 @comment POSIX.1
958 @item STDERR_FILENO
959 This macro has value @code{2}, which is the file descriptor for
960 standard error output.
961 @end vtable
962 @cindex standard error file descriptor
963
964 @node Stream/Descriptor Precautions
965 @section Dangers of Mixing Streams and Descriptors
966 @cindex channels
967 @cindex streams and descriptors
968 @cindex descriptors and streams
969 @cindex mixing descriptors and streams
970
971 You can have multiple file descriptors and streams (let's call both
972 streams and descriptors ``channels'' for short) connected to the same
973 file, but you must take care to avoid confusion between channels. There
974 are two cases to consider: @dfn{linked} channels that share a single
975 file position value, and @dfn{independent} channels that have their own
976 file positions.
977
978 It's best to use just one channel in your program for actual data
979 transfer to any given file, except when all the access is for input.
980 For example, if you open a pipe (something you can only do at the file
981 descriptor level), either do all I/O with the descriptor, or construct a
982 stream from the descriptor with @code{fdopen} and then do all I/O with
983 the stream.
984
985 @menu
986 * Linked Channels:: Dealing with channels sharing a file position.
987 * Independent Channels:: Dealing with separately opened, unlinked channels.
988 * Cleaning Streams:: Cleaning a stream makes it safe to use
989 another channel.
990 @end menu
991
992 @node Linked Channels
993 @subsection Linked Channels
994 @cindex linked channels
995
996 Channels that come from a single opening share the same file position;
997 we call them @dfn{linked} channels. Linked channels result when you
998 make a stream from a descriptor using @code{fdopen}, when you get a
999 descriptor from a stream with @code{fileno}, when you copy a descriptor
1000 with @code{dup} or @code{dup2}, and when descriptors are inherited
1001 during @code{fork}. For files that don't support random access, such as
1002 terminals and pipes, @emph{all} channels are effectively linked. On
1003 random-access files, all append-type output streams are effectively
1004 linked to each other.
1005
1006 @cindex cleaning up a stream
1007 If you have been using a stream for I/O (or have just opened the stream),
1008 and you want to do I/O using
1009 another channel (either a stream or a descriptor) that is linked to it,
1010 you must first @dfn{clean up} the stream that you have been using.
1011 @xref{Cleaning Streams}.
1012
1013 Terminating a process, or executing a new program in the process,
1014 destroys all the streams in the process. If descriptors linked to these
1015 streams persist in other processes, their file positions become
1016 undefined as a result. To prevent this, you must clean up the streams
1017 before destroying them.
1018
1019 @node Independent Channels
1020 @subsection Independent Channels
1021 @cindex independent channels
1022
1023 When you open channels (streams or descriptors) separately on a seekable
1024 file, each channel has its own file position. These are called
1025 @dfn{independent channels}.
1026
1027 The system handles each channel independently. Most of the time, this
1028 is quite predictable and natural (especially for input): each channel
1029 can read or write sequentially at its own place in the file. However,
1030 if some of the channels are streams, you must take these precautions:
1031
1032 @itemize @bullet
1033 @item
1034 You should clean an output stream after use, before doing anything else
1035 that might read or write from the same part of the file.
1036
1037 @item
1038 You should clean an input stream before reading data that may have been
1039 modified using an independent channel. Otherwise, you might read
1040 obsolete data that had been in the stream's buffer.
1041 @end itemize
1042
1043 If you do output to one channel at the end of the file, this will
1044 certainly leave the other independent channels positioned somewhere
1045 before the new end. You cannot reliably set their file positions to the
1046 new end of file before writing, because the file can always be extended
1047 by another process between when you set the file position and when you
1048 write the data. Instead, use an append-type descriptor or stream; they
1049 always output at the current end of the file. In order to make the
1050 end-of-file position accurate, you must clean the output channel you
1051 were using, if it is a stream.
1052
1053 It's impossible for two channels to have separate file pointers for a
1054 file that doesn't support random access. Thus, channels for reading or
1055 writing such files are always linked, never independent. Append-type
1056 channels are also always linked. For these channels, follow the rules
1057 for linked channels; see @ref{Linked Channels}.
1058
1059 @node Cleaning Streams
1060 @subsection Cleaning Streams
1061
1062 You can use @code{fflush} to clean a stream in most
1063 cases.
1064
1065 You can skip the @code{fflush} if you know the stream
1066 is already clean. A stream is clean whenever its buffer is empty. For
1067 example, an unbuffered stream is always clean. An input stream that is
1068 at end-of-file is clean. A line-buffered stream is clean when the last
1069 character output was a newline. However, a just-opened input stream
1070 might not be clean, as its input buffer might not be empty.
1071
1072 There is one case in which cleaning a stream is impossible on most
1073 systems. This is when the stream is doing input from a file that is not
1074 random-access. Such streams typically read ahead, and when the file is
1075 not random access, there is no way to give back the excess data already
1076 read. When an input stream reads from a random-access file,
1077 @code{fflush} does clean the stream, but leaves the file pointer at an
1078 unpredictable place; you must set the file pointer before doing any
1079 further I/O.
1080
1081 Closing an output-only stream also does @code{fflush}, so this is a
1082 valid way of cleaning an output stream.
1083
1084 You need not clean a stream before using its descriptor for control
1085 operations such as setting terminal modes; these operations don't affect
1086 the file position and are not affected by it. You can use any
1087 descriptor for these operations, and all channels are affected
1088 simultaneously. However, text already ``output'' to a stream but still
1089 buffered by the stream will be subject to the new terminal modes when
1090 subsequently flushed. To make sure ``past'' output is covered by the
1091 terminal settings that were in effect at the time, flush the output
1092 streams for that terminal before setting the modes. @xref{Terminal
1093 Modes}.
1094
1095 @node Scatter-Gather
1096 @section Fast Scatter-Gather I/O
1097 @cindex scatter-gather
1098
1099 Some applications may need to read or write data to multiple buffers,
1100 which are separated in memory. Although this can be done easily enough
1101 with multiple calls to @code{read} and @code{write}, it is inefficient
1102 because there is overhead associated with each kernel call.
1103
1104 Instead, many platforms provide special high-speed primitives to perform
1105 these @dfn{scatter-gather} operations in a single kernel call. @Theglibc{}
1106 will provide an emulation on any system that lacks these
1107 primitives, so they are not a portability threat. They are defined in
1108 @code{sys/uio.h}.
1109
1110 These functions are controlled with arrays of @code{iovec} structures,
1111 which describe the location and size of each buffer.
1112
1113 @comment sys/uio.h
1114 @comment BSD
1115 @deftp {Data Type} {struct iovec}
1116
1117 The @code{iovec} structure describes a buffer. It contains two fields:
1118
1119 @table @code
1120
1121 @item void *iov_base
1122 Contains the address of a buffer.
1123
1124 @item size_t iov_len
1125 Contains the length of the buffer.
1126
1127 @end table
1128 @end deftp
1129
1130 @comment sys/uio.h
1131 @comment BSD
1132 @deftypefun ssize_t readv (int @var{filedes}, const struct iovec *@var{vector}, int @var{count})
1133 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1134 @c The fallback sysdeps/posix implementation, used even on GNU/Linux
1135 @c with old kernels that lack a full readv/writev implementation, may
1136 @c malloc the buffer into which data is read, if the total read size is
1137 @c too large for alloca.
1138
1139 The @code{readv} function reads data from @var{filedes} and scatters it
1140 into the buffers described in @var{vector}, which is taken to be
1141 @var{count} structures long. As each buffer is filled, data is sent to the
1142 next.
1143
1144 Note that @code{readv} is not guaranteed to fill all the buffers.
1145 It may stop at any point, for the same reasons @code{read} would.
1146
1147 The return value is a count of bytes (@emph{not} buffers) read, @math{0}
1148 indicating end-of-file, or @math{-1} indicating an error. The possible
1149 errors are the same as in @code{read}.
1150
1151 @end deftypefun
1152
1153 @comment sys/uio.h
1154 @comment BSD
1155 @deftypefun ssize_t writev (int @var{filedes}, const struct iovec *@var{vector}, int @var{count})
1156 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1157 @c The fallback sysdeps/posix implementation, used even on GNU/Linux
1158 @c with old kernels that lack a full readv/writev implementation, may
1159 @c malloc the buffer from which data is written, if the total write size
1160 @c is too large for alloca.
1161
1162 The @code{writev} function gathers data from the buffers described in
1163 @var{vector}, which is taken to be @var{count} structures long, and writes
1164 them to @code{filedes}. As each buffer is written, it moves on to the
1165 next.
1166
1167 Like @code{readv}, @code{writev} may stop midstream under the same
1168 conditions @code{write} would.
1169
1170 The return value is a count of bytes written, or @math{-1} indicating an
1171 error. The possible errors are the same as in @code{write}.
1172
1173 @end deftypefun
1174
1175 @c Note - I haven't read this anywhere. I surmised it from my knowledge
1176 @c of computer science. Thus, there could be subtleties I'm missing.
1177
1178 Note that if the buffers are small (under about 1kB), high-level streams
1179 may be easier to use than these functions. However, @code{readv} and
1180 @code{writev} are more efficient when the individual buffers themselves
1181 (as opposed to the total output), are large. In that case, a high-level
1182 stream would not be able to cache the data efficiently.
1183
1184 @node Memory-mapped I/O
1185 @section Memory-mapped I/O
1186
1187 On modern operating systems, it is possible to @dfn{mmap} (pronounced
1188 ``em-map'') a file to a region of memory. When this is done, the file can
1189 be accessed just like an array in the program.
1190
1191 This is more efficient than @code{read} or @code{write}, as only the regions
1192 of the file that a program actually accesses are loaded. Accesses to
1193 not-yet-loaded parts of the mmapped region are handled in the same way as
1194 swapped out pages.
1195
1196 Since mmapped pages can be stored back to their file when physical
1197 memory is low, it is possible to mmap files orders of magnitude larger
1198 than both the physical memory @emph{and} swap space. The only limit is
1199 address space. The theoretical limit is 4GB on a 32-bit machine -
1200 however, the actual limit will be smaller since some areas will be
1201 reserved for other purposes. If the LFS interface is used the file size
1202 on 32-bit systems is not limited to 2GB (offsets are signed which
1203 reduces the addressable area of 4GB by half); the full 64-bit are
1204 available.
1205
1206 Memory mapping only works on entire pages of memory. Thus, addresses
1207 for mapping must be page-aligned, and length values will be rounded up.
1208 To determine the size of a page the machine uses one should use
1209
1210 @vindex _SC_PAGESIZE
1211 @smallexample
1212 size_t page_size = (size_t) sysconf (_SC_PAGESIZE);
1213 @end smallexample
1214
1215 @noindent
1216 These functions are declared in @file{sys/mman.h}.
1217
1218 @comment sys/mman.h
1219 @comment POSIX
1220 @deftypefun {void *} mmap (void *@var{address}, size_t @var{length}, int @var{protect}, int @var{flags}, int @var{filedes}, off_t @var{offset})
1221 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1222
1223 The @code{mmap} function creates a new mapping, connected to bytes
1224 (@var{offset}) to (@var{offset} + @var{length} - 1) in the file open on
1225 @var{filedes}. A new reference for the file specified by @var{filedes}
1226 is created, which is not removed by closing the file.
1227
1228 @var{address} gives a preferred starting address for the mapping.
1229 @code{NULL} expresses no preference. Any previous mapping at that
1230 address is automatically removed. The address you give may still be
1231 changed, unless you use the @code{MAP_FIXED} flag.
1232
1233 @vindex PROT_READ
1234 @vindex PROT_WRITE
1235 @vindex PROT_EXEC
1236 @var{protect} contains flags that control what kind of access is
1237 permitted. They include @code{PROT_READ}, @code{PROT_WRITE}, and
1238 @code{PROT_EXEC}, which permit reading, writing, and execution,
1239 respectively. Inappropriate access will cause a segfault (@pxref{Program
1240 Error Signals}).
1241
1242 Note that most hardware designs cannot support write permission without
1243 read permission, and many do not distinguish read and execute permission.
1244 Thus, you may receive wider permissions than you ask for, and mappings of
1245 write-only files may be denied even if you do not use @code{PROT_READ}.
1246
1247 @var{flags} contains flags that control the nature of the map.
1248 One of @code{MAP_SHARED} or @code{MAP_PRIVATE} must be specified.
1249
1250 They include:
1251
1252 @vtable @code
1253 @item MAP_PRIVATE
1254 This specifies that writes to the region should never be written back
1255 to the attached file. Instead, a copy is made for the process, and the
1256 region will be swapped normally if memory runs low. No other process will
1257 see the changes.
1258
1259 Since private mappings effectively revert to ordinary memory
1260 when written to, you must have enough virtual memory for a copy of
1261 the entire mmapped region if you use this mode with @code{PROT_WRITE}.
1262
1263 @item MAP_SHARED
1264 This specifies that writes to the region will be written back to the
1265 file. Changes made will be shared immediately with other processes
1266 mmaping the same file.
1267
1268 Note that actual writing may take place at any time. You need to use
1269 @code{msync}, described below, if it is important that other processes
1270 using conventional I/O get a consistent view of the file.
1271
1272 @item MAP_FIXED
1273 This forces the system to use the exact mapping address specified in
1274 @var{address} and fail if it can't.
1275
1276 @c One of these is official - the other is obviously an obsolete synonym
1277 @c Which is which?
1278 @item MAP_ANONYMOUS
1279 @itemx MAP_ANON
1280 This flag tells the system to create an anonymous mapping, not connected
1281 to a file. @var{filedes} and @var{offset} are ignored, and the region is
1282 initialized with zeros.
1283
1284 Anonymous maps are used as the basic primitive to extend the heap on some
1285 systems. They are also useful to share data between multiple tasks
1286 without creating a file.
1287
1288 On some systems using private anonymous mmaps is more efficient than using
1289 @code{malloc} for large blocks. This is not an issue with @theglibc{},
1290 as the included @code{malloc} automatically uses @code{mmap} where appropriate.
1291
1292 @c Linux has some other MAP_ options, which I have not discussed here.
1293 @c MAP_DENYWRITE, MAP_EXECUTABLE and MAP_GROWSDOWN don't seem applicable to
1294 @c user programs (and I don't understand the last two). MAP_LOCKED does
1295 @c not appear to be implemented.
1296
1297 @end vtable
1298
1299 @code{mmap} returns the address of the new mapping, or
1300 @code{MAP_FAILED} for an error.
1301
1302 Possible errors include:
1303
1304 @table @code
1305
1306 @item EINVAL
1307
1308 Either @var{address} was unusable, or inconsistent @var{flags} were
1309 given.
1310
1311 @item EACCES
1312
1313 @var{filedes} was not open for the type of access specified in @var{protect}.
1314
1315 @item ENOMEM
1316
1317 Either there is not enough memory for the operation, or the process is
1318 out of address space.
1319
1320 @item ENODEV
1321
1322 This file is of a type that doesn't support mapping.
1323
1324 @item ENOEXEC
1325
1326 The file is on a filesystem that doesn't support mapping.
1327
1328 @c On Linux, EAGAIN will appear if the file has a conflicting mandatory lock.
1329 @c However mandatory locks are not discussed in this manual.
1330 @c
1331 @c Similarly, ETXTBSY will occur if the MAP_DENYWRITE flag (not documented
1332 @c here) is used and the file is already open for writing.
1333
1334 @end table
1335
1336 @end deftypefun
1337
1338 @comment sys/mman.h
1339 @comment LFS
1340 @deftypefun {void *} mmap64 (void *@var{address}, size_t @var{length}, int @var{protect}, int @var{flags}, int @var{filedes}, off64_t @var{offset})
1341 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1342 @c The page_shift auto detection when MMAP2_PAGE_SHIFT is -1 (it never
1343 @c is) would be thread-unsafe.
1344 The @code{mmap64} function is equivalent to the @code{mmap} function but
1345 the @var{offset} parameter is of type @code{off64_t}. On 32-bit systems
1346 this allows the file associated with the @var{filedes} descriptor to be
1347 larger than 2GB. @var{filedes} must be a descriptor returned from a
1348 call to @code{open64} or @code{fopen64} and @code{freopen64} where the
1349 descriptor is retrieved with @code{fileno}.
1350
1351 When the sources are translated with @code{_FILE_OFFSET_BITS == 64} this
1352 function is actually available under the name @code{mmap}. I.e., the
1353 new, extended API using 64 bit file sizes and offsets transparently
1354 replaces the old API.
1355 @end deftypefun
1356
1357 @comment sys/mman.h
1358 @comment POSIX
1359 @deftypefun int munmap (void *@var{addr}, size_t @var{length})
1360 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1361
1362 @code{munmap} removes any memory maps from (@var{addr}) to (@var{addr} +
1363 @var{length}). @var{length} should be the length of the mapping.
1364
1365 It is safe to unmap multiple mappings in one command, or include unmapped
1366 space in the range. It is also possible to unmap only part of an existing
1367 mapping. However, only entire pages can be removed. If @var{length} is not
1368 an even number of pages, it will be rounded up.
1369
1370 It returns @math{0} for success and @math{-1} for an error.
1371
1372 One error is possible:
1373
1374 @table @code
1375
1376 @item EINVAL
1377 The memory range given was outside the user mmap range or wasn't page
1378 aligned.
1379
1380 @end table
1381
1382 @end deftypefun
1383
1384 @comment sys/mman.h
1385 @comment POSIX
1386 @deftypefun int msync (void *@var{address}, size_t @var{length}, int @var{flags})
1387 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1388
1389 When using shared mappings, the kernel can write the file at any time
1390 before the mapping is removed. To be certain data has actually been
1391 written to the file and will be accessible to non-memory-mapped I/O, it
1392 is necessary to use this function.
1393
1394 It operates on the region @var{address} to (@var{address} + @var{length}).
1395 It may be used on part of a mapping or multiple mappings, however the
1396 region given should not contain any unmapped space.
1397
1398 @var{flags} can contain some options:
1399
1400 @vtable @code
1401
1402 @item MS_SYNC
1403
1404 This flag makes sure the data is actually written @emph{to disk}.
1405 Normally @code{msync} only makes sure that accesses to a file with
1406 conventional I/O reflect the recent changes.
1407
1408 @item MS_ASYNC
1409
1410 This tells @code{msync} to begin the synchronization, but not to wait for
1411 it to complete.
1412
1413 @c Linux also has MS_INVALIDATE, which I don't understand.
1414
1415 @end vtable
1416
1417 @code{msync} returns @math{0} for success and @math{-1} for
1418 error. Errors include:
1419
1420 @table @code
1421
1422 @item EINVAL
1423 An invalid region was given, or the @var{flags} were invalid.
1424
1425 @item EFAULT
1426 There is no existing mapping in at least part of the given region.
1427
1428 @end table
1429
1430 @end deftypefun
1431
1432 @comment sys/mman.h
1433 @comment GNU
1434 @deftypefun {void *} mremap (void *@var{address}, size_t @var{length}, size_t @var{new_length}, int @var{flag})
1435 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1436
1437 This function can be used to change the size of an existing memory
1438 area. @var{address} and @var{length} must cover a region entirely mapped
1439 in the same @code{mmap} statement. A new mapping with the same
1440 characteristics will be returned with the length @var{new_length}.
1441
1442 One option is possible, @code{MREMAP_MAYMOVE}. If it is given in
1443 @var{flags}, the system may remove the existing mapping and create a new
1444 one of the desired length in another location.
1445
1446 The address of the resulting mapping is returned, or @math{-1}. Possible
1447 error codes include:
1448
1449 @table @code
1450
1451 @item EFAULT
1452 There is no existing mapping in at least part of the original region, or
1453 the region covers two or more distinct mappings.
1454
1455 @item EINVAL
1456 The address given is misaligned or inappropriate.
1457
1458 @item EAGAIN
1459 The region has pages locked, and if extended it would exceed the
1460 process's resource limit for locked pages. @xref{Limits on Resources}.
1461
1462 @item ENOMEM
1463 The region is private writable, and insufficient virtual memory is
1464 available to extend it. Also, this error will occur if
1465 @code{MREMAP_MAYMOVE} is not given and the extension would collide with
1466 another mapped region.
1467
1468 @end table
1469 @end deftypefun
1470
1471 This function is only available on a few systems. Except for performing
1472 optional optimizations one should not rely on this function.
1473
1474 Not all file descriptors may be mapped. Sockets, pipes, and most devices
1475 only allow sequential access and do not fit into the mapping abstraction.
1476 In addition, some regular files may not be mmapable, and older kernels may
1477 not support mapping at all. Thus, programs using @code{mmap} should
1478 have a fallback method to use should it fail. @xref{Mmap,,,standards,GNU
1479 Coding Standards}.
1480
1481 @comment sys/mman.h
1482 @comment POSIX
1483 @deftypefun int madvise (void *@var{addr}, size_t @var{length}, int @var{advice})
1484 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1485
1486 This function can be used to provide the system with @var{advice} about
1487 the intended usage patterns of the memory region starting at @var{addr}
1488 and extending @var{length} bytes.
1489
1490 The valid BSD values for @var{advice} are:
1491
1492 @vtable @code
1493
1494 @item MADV_NORMAL
1495 The region should receive no further special treatment.
1496
1497 @item MADV_RANDOM
1498 The region will be accessed via random page references. The kernel
1499 should page-in the minimal number of pages for each page fault.
1500
1501 @item MADV_SEQUENTIAL
1502 The region will be accessed via sequential page references. This
1503 may cause the kernel to aggressively read-ahead, expecting further
1504 sequential references after any page fault within this region.
1505
1506 @item MADV_WILLNEED
1507 The region will be needed. The pages within this region may
1508 be pre-faulted in by the kernel.
1509
1510 @item MADV_DONTNEED
1511 The region is no longer needed. The kernel may free these pages,
1512 causing any changes to the pages to be lost, as well as swapped
1513 out pages to be discarded.
1514
1515 @end vtable
1516
1517 The POSIX names are slightly different, but with the same meanings:
1518
1519 @vtable @code
1520
1521 @item POSIX_MADV_NORMAL
1522 This corresponds with BSD's @code{MADV_NORMAL}.
1523
1524 @item POSIX_MADV_RANDOM
1525 This corresponds with BSD's @code{MADV_RANDOM}.
1526
1527 @item POSIX_MADV_SEQUENTIAL
1528 This corresponds with BSD's @code{MADV_SEQUENTIAL}.
1529
1530 @item POSIX_MADV_WILLNEED
1531 This corresponds with BSD's @code{MADV_WILLNEED}.
1532
1533 @item POSIX_MADV_DONTNEED
1534 This corresponds with BSD's @code{MADV_DONTNEED}.
1535
1536 @end vtable
1537
1538 @code{madvise} returns @math{0} for success and @math{-1} for
1539 error. Errors include:
1540 @table @code
1541
1542 @item EINVAL
1543 An invalid region was given, or the @var{advice} was invalid.
1544
1545 @item EFAULT
1546 There is no existing mapping in at least part of the given region.
1547
1548 @end table
1549 @end deftypefun
1550
1551 @comment sys/mman.h
1552 @comment POSIX
1553 @deftypefn Function int shm_open (const char *@var{name}, int @var{oflag}, mode_t @var{mode})
1554 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asuinit{} @ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1555 @c shm_open @mtslocale @asuinit @ascuheap @asulock @aculock @acsmem @acsfd
1556 @c libc_once(where_is_shmfs) @mtslocale @asuinit @ascuheap @asulock @aculock @acsmem @acsfd
1557 @c where_is_shmfs @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1558 @c statfs dup ok
1559 @c setmntent dup @ascuheap @asulock @acsmem @acsfd @aculock
1560 @c getmntent_r dup @mtslocale @ascuheap @aculock @acsmem [no @asucorrupt @acucorrupt; exclusive stream]
1561 @c strcmp dup ok
1562 @c strlen dup ok
1563 @c malloc dup @ascuheap @acsmem
1564 @c mempcpy dup ok
1565 @c endmntent dup @ascuheap @asulock @aculock @acsmem @acsfd
1566 @c strlen dup ok
1567 @c strchr dup ok
1568 @c mempcpy dup ok
1569 @c open dup @acsfd
1570 @c fcntl dup ok
1571 @c close dup @acsfd
1572
1573 This function returns a file descriptor that can be used to allocate shared
1574 memory via mmap. Unrelated processes can use same @var{name} to create or
1575 open existing shared memory objects.
1576
1577 A @var{name} argument specifies the shared memory object to be opened.
1578 In @theglibc{} it must be a string smaller than @code{NAME_MAX} bytes starting
1579 with an optional slash but containing no other slashes.
1580
1581 The semantics of @var{oflag} and @var{mode} arguments is same as in @code{open}.
1582
1583 @code{shm_open} returns the file descriptor on success or @math{-1} on error.
1584 On failure @code{errno} is set.
1585 @end deftypefn
1586
1587 @deftypefn Function int shm_unlink (const char *@var{name})
1588 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asuinit{} @ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1589 @c shm_unlink @mtslocale @asuinit @ascuheap @asulock @aculock @acsmem @acsfd
1590 @c libc_once(where_is_shmfs) dup @mtslocale @asuinit @ascuheap @asulock @aculock @acsmem @acsfd
1591 @c strlen dup ok
1592 @c strchr dup ok
1593 @c mempcpy dup ok
1594 @c unlink dup ok
1595
1596 This function is the inverse of @code{shm_open} and removes the object with
1597 the given @var{name} previously created by @code{shm_open}.
1598
1599 @code{shm_unlink} returns @math{0} on success or @math{-1} on error.
1600 On failure @code{errno} is set.
1601 @end deftypefn
1602
1603 @node Waiting for I/O
1604 @section Waiting for Input or Output
1605 @cindex waiting for input or output
1606 @cindex multiplexing input
1607 @cindex input from multiple files
1608
1609 Sometimes a program needs to accept input on multiple input channels
1610 whenever input arrives. For example, some workstations may have devices
1611 such as a digitizing tablet, function button box, or dial box that are
1612 connected via normal asynchronous serial interfaces; good user interface
1613 style requires responding immediately to input on any device. Another
1614 example is a program that acts as a server to several other processes
1615 via pipes or sockets.
1616
1617 You cannot normally use @code{read} for this purpose, because this
1618 blocks the program until input is available on one particular file
1619 descriptor; input on other channels won't wake it up. You could set
1620 nonblocking mode and poll each file descriptor in turn, but this is very
1621 inefficient.
1622
1623 A better solution is to use the @code{select} function. This blocks the
1624 program until input or output is ready on a specified set of file
1625 descriptors, or until a timer expires, whichever comes first. This
1626 facility is declared in the header file @file{sys/types.h}.
1627 @pindex sys/types.h
1628
1629 In the case of a server socket (@pxref{Listening}), we say that
1630 ``input'' is available when there are pending connections that could be
1631 accepted (@pxref{Accepting Connections}). @code{accept} for server
1632 sockets blocks and interacts with @code{select} just as @code{read} does
1633 for normal input.
1634
1635 @cindex file descriptor sets, for @code{select}
1636 The file descriptor sets for the @code{select} function are specified
1637 as @code{fd_set} objects. Here is the description of the data type
1638 and some macros for manipulating these objects.
1639
1640 @comment sys/types.h
1641 @comment BSD
1642 @deftp {Data Type} fd_set
1643 The @code{fd_set} data type represents file descriptor sets for the
1644 @code{select} function. It is actually a bit array.
1645 @end deftp
1646
1647 @comment sys/types.h
1648 @comment BSD
1649 @deftypevr Macro int FD_SETSIZE
1650 The value of this macro is the maximum number of file descriptors that a
1651 @code{fd_set} object can hold information about. On systems with a
1652 fixed maximum number, @code{FD_SETSIZE} is at least that number. On
1653 some systems, including GNU, there is no absolute limit on the number of
1654 descriptors open, but this macro still has a constant value which
1655 controls the number of bits in an @code{fd_set}; if you get a file
1656 descriptor with a value as high as @code{FD_SETSIZE}, you cannot put
1657 that descriptor into an @code{fd_set}.
1658 @end deftypevr
1659
1660 @comment sys/types.h
1661 @comment BSD
1662 @deftypefn Macro void FD_ZERO (fd_set *@var{set})
1663 @safety{@prelim{}@mtsafe{@mtsrace{:set}}@assafe{}@acsafe{}}
1664 This macro initializes the file descriptor set @var{set} to be the
1665 empty set.
1666 @end deftypefn
1667
1668 @comment sys/types.h
1669 @comment BSD
1670 @deftypefn Macro void FD_SET (int @var{filedes}, fd_set *@var{set})
1671 @safety{@prelim{}@mtsafe{@mtsrace{:set}}@assafe{}@acsafe{}}
1672 @c Setting a bit isn't necessarily atomic, so there's a potential race
1673 @c here if set is not used exclusively.
1674 This macro adds @var{filedes} to the file descriptor set @var{set}.
1675
1676 The @var{filedes} parameter must not have side effects since it is
1677 evaluated more than once.
1678 @end deftypefn
1679
1680 @comment sys/types.h
1681 @comment BSD
1682 @deftypefn Macro void FD_CLR (int @var{filedes}, fd_set *@var{set})
1683 @safety{@prelim{}@mtsafe{@mtsrace{:set}}@assafe{}@acsafe{}}
1684 @c Setting a bit isn't necessarily atomic, so there's a potential race
1685 @c here if set is not used exclusively.
1686 This macro removes @var{filedes} from the file descriptor set @var{set}.
1687
1688 The @var{filedes} parameter must not have side effects since it is
1689 evaluated more than once.
1690 @end deftypefn
1691
1692 @comment sys/types.h
1693 @comment BSD
1694 @deftypefn Macro int FD_ISSET (int @var{filedes}, const fd_set *@var{set})
1695 @safety{@prelim{}@mtsafe{@mtsrace{:set}}@assafe{}@acsafe{}}
1696 This macro returns a nonzero value (true) if @var{filedes} is a member
1697 of the file descriptor set @var{set}, and zero (false) otherwise.
1698
1699 The @var{filedes} parameter must not have side effects since it is
1700 evaluated more than once.
1701 @end deftypefn
1702
1703 Next, here is the description of the @code{select} function itself.
1704
1705 @comment sys/types.h
1706 @comment BSD
1707 @deftypefun int select (int @var{nfds}, fd_set *@var{read-fds}, fd_set *@var{write-fds}, fd_set *@var{except-fds}, struct timeval *@var{timeout})
1708 @safety{@prelim{}@mtsafe{@mtsrace{:read-fds} @mtsrace{:write-fds} @mtsrace{:except-fds}}@assafe{}@acsafe{}}
1709 @c The select syscall is preferred, but pselect6 may be used instead,
1710 @c which requires converting timeout to a timespec and back. The
1711 @c conversions are not atomic.
1712 The @code{select} function blocks the calling process until there is
1713 activity on any of the specified sets of file descriptors, or until the
1714 timeout period has expired.
1715
1716 The file descriptors specified by the @var{read-fds} argument are
1717 checked to see if they are ready for reading; the @var{write-fds} file
1718 descriptors are checked to see if they are ready for writing; and the
1719 @var{except-fds} file descriptors are checked for exceptional
1720 conditions. You can pass a null pointer for any of these arguments if
1721 you are not interested in checking for that kind of condition.
1722
1723 A file descriptor is considered ready for reading if a @code{read}
1724 call will not block. This usually includes the read offset being at
1725 the end of the file or there is an error to report. A server socket
1726 is considered ready for reading if there is a pending connection which
1727 can be accepted with @code{accept}; @pxref{Accepting Connections}. A
1728 client socket is ready for writing when its connection is fully
1729 established; @pxref{Connecting}.
1730
1731 ``Exceptional conditions'' does not mean errors---errors are reported
1732 immediately when an erroneous system call is executed, and do not
1733 constitute a state of the descriptor. Rather, they include conditions
1734 such as the presence of an urgent message on a socket. (@xref{Sockets},
1735 for information on urgent messages.)
1736
1737 The @code{select} function checks only the first @var{nfds} file
1738 descriptors. The usual thing is to pass @code{FD_SETSIZE} as the value
1739 of this argument.
1740
1741 The @var{timeout} specifies the maximum time to wait. If you pass a
1742 null pointer for this argument, it means to block indefinitely until one
1743 of the file descriptors is ready. Otherwise, you should provide the
1744 time in @code{struct timeval} format; see @ref{High-Resolution
1745 Calendar}. Specify zero as the time (a @code{struct timeval} containing
1746 all zeros) if you want to find out which descriptors are ready without
1747 waiting if none are ready.
1748
1749 The normal return value from @code{select} is the total number of ready file
1750 descriptors in all of the sets. Each of the argument sets is overwritten
1751 with information about the descriptors that are ready for the corresponding
1752 operation. Thus, to see if a particular descriptor @var{desc} has input,
1753 use @code{FD_ISSET (@var{desc}, @var{read-fds})} after @code{select} returns.
1754
1755 If @code{select} returns because the timeout period expires, it returns
1756 a value of zero.
1757
1758 Any signal will cause @code{select} to return immediately. So if your
1759 program uses signals, you can't rely on @code{select} to keep waiting
1760 for the full time specified. If you want to be sure of waiting for a
1761 particular amount of time, you must check for @code{EINTR} and repeat
1762 the @code{select} with a newly calculated timeout based on the current
1763 time. See the example below. See also @ref{Interrupted Primitives}.
1764
1765 If an error occurs, @code{select} returns @code{-1} and does not modify
1766 the argument file descriptor sets. The following @code{errno} error
1767 conditions are defined for this function:
1768
1769 @table @code
1770 @item EBADF
1771 One of the file descriptor sets specified an invalid file descriptor.
1772
1773 @item EINTR
1774 The operation was interrupted by a signal. @xref{Interrupted Primitives}.
1775
1776 @item EINVAL
1777 The @var{timeout} argument is invalid; one of the components is negative
1778 or too large.
1779 @end table
1780 @end deftypefun
1781
1782 @strong{Portability Note:} The @code{select} function is a BSD Unix
1783 feature.
1784
1785 Here is an example showing how you can use @code{select} to establish a
1786 timeout period for reading from a file descriptor. The @code{input_timeout}
1787 function blocks the calling process until input is available on the
1788 file descriptor, or until the timeout period expires.
1789
1790 @smallexample
1791 @include select.c.texi
1792 @end smallexample
1793
1794 There is another example showing the use of @code{select} to multiplex
1795 input from multiple sockets in @ref{Server Example}.
1796
1797
1798 @node Synchronizing I/O
1799 @section Synchronizing I/O operations
1800
1801 @cindex synchronizing
1802 In most modern operating systems, the normal I/O operations are not
1803 executed synchronously. I.e., even if a @code{write} system call
1804 returns, this does not mean the data is actually written to the media,
1805 e.g., the disk.
1806
1807 In situations where synchronization points are necessary, you can use
1808 special functions which ensure that all operations finish before
1809 they return.
1810
1811 @comment unistd.h
1812 @comment X/Open
1813 @deftypefun void sync (void)
1814 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1815 A call to this function will not return as long as there is data which
1816 has not been written to the device. All dirty buffers in the kernel will
1817 be written and so an overall consistent system can be achieved (if no
1818 other process in parallel writes data).
1819
1820 A prototype for @code{sync} can be found in @file{unistd.h}.
1821 @end deftypefun
1822
1823 Programs more often want to ensure that data written to a given file is
1824 committed, rather than all data in the system. For this, @code{sync} is overkill.
1825
1826
1827 @comment unistd.h
1828 @comment POSIX
1829 @deftypefun int fsync (int @var{fildes})
1830 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1831 The @code{fsync} function can be used to make sure all data associated with
1832 the open file @var{fildes} is written to the device associated with the
1833 descriptor. The function call does not return unless all actions have
1834 finished.
1835
1836 A prototype for @code{fsync} can be found in @file{unistd.h}.
1837
1838 This function is a cancellation point in multi-threaded programs. This
1839 is a problem if the thread allocates some resources (like memory, file
1840 descriptors, semaphores or whatever) at the time @code{fsync} is
1841 called. If the thread gets canceled these resources stay allocated
1842 until the program ends. To avoid this, calls to @code{fsync} should be
1843 protected using cancellation handlers.
1844 @c ref pthread_cleanup_push / pthread_cleanup_pop
1845
1846 The return value of the function is zero if no error occurred. Otherwise
1847 it is @math{-1} and the global variable @var{errno} is set to the
1848 following values:
1849 @table @code
1850 @item EBADF
1851 The descriptor @var{fildes} is not valid.
1852
1853 @item EINVAL
1854 No synchronization is possible since the system does not implement this.
1855 @end table
1856 @end deftypefun
1857
1858 Sometimes it is not even necessary to write all data associated with a
1859 file descriptor. E.g., in database files which do not change in size it
1860 is enough to write all the file content data to the device.
1861 Meta-information, like the modification time etc., are not that important
1862 and leaving such information uncommitted does not prevent a successful
1863 recovery of the file in case of a problem.
1864
1865 @comment unistd.h
1866 @comment POSIX
1867 @deftypefun int fdatasync (int @var{fildes})
1868 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1869 When a call to the @code{fdatasync} function returns, it is ensured
1870 that all of the file data is written to the device. For all pending I/O
1871 operations, the parts guaranteeing data integrity finished.
1872
1873 Not all systems implement the @code{fdatasync} operation. On systems
1874 missing this functionality @code{fdatasync} is emulated by a call to
1875 @code{fsync} since the performed actions are a superset of those
1876 required by @code{fdatasync}.
1877
1878 The prototype for @code{fdatasync} is in @file{unistd.h}.
1879
1880 The return value of the function is zero if no error occurred. Otherwise
1881 it is @math{-1} and the global variable @var{errno} is set to the
1882 following values:
1883 @table @code
1884 @item EBADF
1885 The descriptor @var{fildes} is not valid.
1886
1887 @item EINVAL
1888 No synchronization is possible since the system does not implement this.
1889 @end table
1890 @end deftypefun
1891
1892
1893 @node Asynchronous I/O
1894 @section Perform I/O Operations in Parallel
1895
1896 The POSIX.1b standard defines a new set of I/O operations which can
1897 significantly reduce the time an application spends waiting for I/O. The
1898 new functions allow a program to initiate one or more I/O operations and
1899 then immediately resume normal work while the I/O operations are
1900 executed in parallel. This functionality is available if the
1901 @file{unistd.h} file defines the symbol @code{_POSIX_ASYNCHRONOUS_IO}.
1902
1903 These functions are part of the library with realtime functions named
1904 @file{librt}. They are not actually part of the @file{libc} binary.
1905 The implementation of these functions can be done using support in the
1906 kernel (if available) or using an implementation based on threads at
1907 userlevel. In the latter case it might be necessary to link applications
1908 with the thread library @file{libpthread} in addition to @file{librt}.
1909
1910 All AIO operations operate on files which were opened previously. There
1911 might be arbitrarily many operations running for one file. The
1912 asynchronous I/O operations are controlled using a data structure named
1913 @code{struct aiocb} (@dfn{AIO control block}). It is defined in
1914 @file{aio.h} as follows.
1915
1916 @comment aio.h
1917 @comment POSIX.1b
1918 @deftp {Data Type} {struct aiocb}
1919 The POSIX.1b standard mandates that the @code{struct aiocb} structure
1920 contains at least the members described in the following table. There
1921 might be more elements which are used by the implementation, but
1922 depending upon these elements is not portable and is highly deprecated.
1923
1924 @table @code
1925 @item int aio_fildes
1926 This element specifies the file descriptor to be used for the
1927 operation. It must be a legal descriptor, otherwise the operation will
1928 fail.
1929
1930 The device on which the file is opened must allow the seek operation.
1931 I.e., it is not possible to use any of the AIO operations on devices
1932 like terminals where an @code{lseek} call would lead to an error.
1933
1934 @item off_t aio_offset
1935 This element specifies the offset in the file at which the operation (input
1936 or output) is performed. Since the operations are carried out in arbitrary
1937 order and more than one operation for one file descriptor can be
1938 started, one cannot expect a current read/write position of the file
1939 descriptor.
1940
1941 @item volatile void *aio_buf
1942 This is a pointer to the buffer with the data to be written or the place
1943 where the read data is stored.
1944
1945 @item size_t aio_nbytes
1946 This element specifies the length of the buffer pointed to by @code{aio_buf}.
1947
1948 @item int aio_reqprio
1949 If the platform has defined @code{_POSIX_PRIORITIZED_IO} and
1950 @code{_POSIX_PRIORITY_SCHEDULING}, the AIO requests are
1951 processed based on the current scheduling priority. The
1952 @code{aio_reqprio} element can then be used to lower the priority of the
1953 AIO operation.
1954
1955 @item struct sigevent aio_sigevent
1956 This element specifies how the calling process is notified once the
1957 operation terminates. If the @code{sigev_notify} element is
1958 @code{SIGEV_NONE}, no notification is sent. If it is @code{SIGEV_SIGNAL},
1959 the signal determined by @code{sigev_signo} is sent. Otherwise,
1960 @code{sigev_notify} must be @code{SIGEV_THREAD}. In this case, a thread
1961 is created which starts executing the function pointed to by
1962 @code{sigev_notify_function}.
1963
1964 @item int aio_lio_opcode
1965 This element is only used by the @code{lio_listio} and
1966 @code{lio_listio64} functions. Since these functions allow an
1967 arbitrary number of operations to start at once, and each operation can be
1968 input or output (or nothing), the information must be stored in the
1969 control block. The possible values are:
1970
1971 @vtable @code
1972 @item LIO_READ
1973 Start a read operation. Read from the file at position
1974 @code{aio_offset} and store the next @code{aio_nbytes} bytes in the
1975 buffer pointed to by @code{aio_buf}.
1976
1977 @item LIO_WRITE
1978 Start a write operation. Write @code{aio_nbytes} bytes starting at
1979 @code{aio_buf} into the file starting at position @code{aio_offset}.
1980
1981 @item LIO_NOP
1982 Do nothing for this control block. This value is useful sometimes when
1983 an array of @code{struct aiocb} values contains holes, i.e., some of the
1984 values must not be handled although the whole array is presented to the
1985 @code{lio_listio} function.
1986 @end vtable
1987 @end table
1988
1989 When the sources are compiled using @code{_FILE_OFFSET_BITS == 64} on a
1990 32 bit machine, this type is in fact @code{struct aiocb64}, since the LFS
1991 interface transparently replaces the @code{struct aiocb} definition.
1992 @end deftp
1993
1994 For use with the AIO functions defined in the LFS, there is a similar type
1995 defined which replaces the types of the appropriate members with larger
1996 types but otherwise is equivalent to @code{struct aiocb}. Particularly,
1997 all member names are the same.
1998
1999 @comment aio.h
2000 @comment POSIX.1b
2001 @deftp {Data Type} {struct aiocb64}
2002 @table @code
2003 @item int aio_fildes
2004 This element specifies the file descriptor which is used for the
2005 operation. It must be a legal descriptor since otherwise the operation
2006 fails for obvious reasons.
2007
2008 The device on which the file is opened must allow the seek operation.
2009 I.e., it is not possible to use any of the AIO operations on devices
2010 like terminals where an @code{lseek} call would lead to an error.
2011
2012 @item off64_t aio_offset
2013 This element specifies at which offset in the file the operation (input
2014 or output) is performed. Since the operation are carried in arbitrary
2015 order and more than one operation for one file descriptor can be
2016 started, one cannot expect a current read/write position of the file
2017 descriptor.
2018
2019 @item volatile void *aio_buf
2020 This is a pointer to the buffer with the data to be written or the place
2021 where the read data is stored.
2022
2023 @item size_t aio_nbytes
2024 This element specifies the length of the buffer pointed to by @code{aio_buf}.
2025
2026 @item int aio_reqprio
2027 If for the platform @code{_POSIX_PRIORITIZED_IO} and
2028 @code{_POSIX_PRIORITY_SCHEDULING} are defined the AIO requests are
2029 processed based on the current scheduling priority. The
2030 @code{aio_reqprio} element can then be used to lower the priority of the
2031 AIO operation.
2032
2033 @item struct sigevent aio_sigevent
2034 This element specifies how the calling process is notified once the
2035 operation terminates. If the @code{sigev_notify} element is
2036 @code{SIGEV_NONE} no notification is sent. If it is @code{SIGEV_SIGNAL},
2037 the signal determined by @code{sigev_signo} is sent. Otherwise,
2038 @code{sigev_notify} must be @code{SIGEV_THREAD} in which case a thread
2039 is created which starts executing the function pointed to by
2040 @code{sigev_notify_function}.
2041
2042 @item int aio_lio_opcode
2043 This element is only used by the @code{lio_listio} and
2044 @code{lio_listio64} functions. Since these functions allow an
2045 arbitrary number of operations to start at once, and since each operation can be
2046 input or output (or nothing), the information must be stored in the
2047 control block. See the description of @code{struct aiocb} for a description
2048 of the possible values.
2049 @end table
2050
2051 When the sources are compiled using @code{_FILE_OFFSET_BITS == 64} on a
2052 32 bit machine, this type is available under the name @code{struct
2053 aiocb64}, since the LFS transparently replaces the old interface.
2054 @end deftp
2055
2056 @menu
2057 * Asynchronous Reads/Writes:: Asynchronous Read and Write Operations.
2058 * Status of AIO Operations:: Getting the Status of AIO Operations.
2059 * Synchronizing AIO Operations:: Getting into a consistent state.
2060 * Cancel AIO Operations:: Cancellation of AIO Operations.
2061 * Configuration of AIO:: How to optimize the AIO implementation.
2062 @end menu
2063
2064 @node Asynchronous Reads/Writes
2065 @subsection Asynchronous Read and Write Operations
2066
2067 @comment aio.h
2068 @comment POSIX.1b
2069 @deftypefun int aio_read (struct aiocb *@var{aiocbp})
2070 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2071 @c Calls aio_enqueue_request.
2072 @c aio_enqueue_request @asulock @ascuheap @aculock @acsmem
2073 @c pthread_self ok
2074 @c pthread_getschedparam @asulock @aculock
2075 @c lll_lock (pthread descriptor's lock) @asulock @aculock
2076 @c sched_getparam ok
2077 @c sched_getscheduler ok
2078 @c lll_unlock @aculock
2079 @c pthread_mutex_lock (aio_requests_mutex) @asulock @aculock
2080 @c get_elem @ascuheap @acsmem [@asucorrupt @acucorrupt]
2081 @c realloc @ascuheap @acsmem
2082 @c calloc @ascuheap @acsmem
2083 @c aio_create_helper_thread @asulock @ascuheap @aculock @acsmem
2084 @c pthread_attr_init ok
2085 @c pthread_attr_setdetachstate ok
2086 @c pthread_get_minstack ok
2087 @c pthread_attr_setstacksize ok
2088 @c sigfillset ok
2089 @c memset ok
2090 @c sigdelset ok
2091 @c SYSCALL rt_sigprocmask ok
2092 @c pthread_create @asulock @ascuheap @aculock @acsmem
2093 @c lll_lock (default_pthread_attr_lock) @asulock @aculock
2094 @c alloca/malloc @ascuheap @acsmem
2095 @c lll_unlock @aculock
2096 @c allocate_stack @asulock @ascuheap @aculock @acsmem
2097 @c getpagesize dup
2098 @c lll_lock (default_pthread_attr_lock) @asulock @aculock
2099 @c lll_unlock @aculock
2100 @c _dl_allocate_tls @ascuheap @acsmem
2101 @c _dl_allocate_tls_storage @ascuheap @acsmem
2102 @c memalign @ascuheap @acsmem
2103 @c memset ok
2104 @c allocate_dtv dup
2105 @c free @ascuheap @acsmem
2106 @c allocate_dtv @ascuheap @acsmem
2107 @c calloc @ascuheap @acsmem
2108 @c INSTALL_DTV ok
2109 @c list_add dup
2110 @c get_cached_stack
2111 @c lll_lock (stack_cache_lock) @asulock @aculock
2112 @c list_for_each ok
2113 @c list_entry dup
2114 @c FREE_P dup
2115 @c stack_list_del dup
2116 @c stack_list_add dup
2117 @c lll_unlock @aculock
2118 @c _dl_allocate_tls_init ok
2119 @c GET_DTV ok
2120 @c mmap ok
2121 @c atomic_increment_val ok
2122 @c munmap ok
2123 @c change_stack_perm ok
2124 @c mprotect ok
2125 @c mprotect ok
2126 @c stack_list_del dup
2127 @c _dl_deallocate_tls dup
2128 @c munmap ok
2129 @c THREAD_COPY_STACK_GUARD ok
2130 @c THREAD_COPY_POINTER_GUARD ok
2131 @c atomic_exchange_acq ok
2132 @c lll_futex_wake ok
2133 @c deallocate_stack @asulock @ascuheap @aculock @acsmem
2134 @c lll_lock (state_cache_lock) @asulock @aculock
2135 @c stack_list_del ok
2136 @c atomic_write_barrier ok
2137 @c list_del ok
2138 @c atomic_write_barrier ok
2139 @c queue_stack @ascuheap @acsmem
2140 @c stack_list_add ok
2141 @c atomic_write_barrier ok
2142 @c list_add ok
2143 @c atomic_write_barrier ok
2144 @c free_stacks @ascuheap @acsmem
2145 @c list_for_each_prev_safe ok
2146 @c list_entry ok
2147 @c FREE_P ok
2148 @c stack_list_del dup
2149 @c _dl_deallocate_tls dup
2150 @c munmap ok
2151 @c _dl_deallocate_tls @ascuheap @acsmem
2152 @c free @ascuheap @acsmem
2153 @c lll_unlock @aculock
2154 @c create_thread @asulock @ascuheap @aculock @acsmem
2155 @c td_eventword
2156 @c td_eventmask
2157 @c do_clone @asulock @ascuheap @aculock @acsmem
2158 @c PREPARE_CREATE ok
2159 @c lll_lock (pd->lock) @asulock @aculock
2160 @c atomic_increment ok
2161 @c clone ok
2162 @c atomic_decrement ok
2163 @c atomic_exchange_acq ok
2164 @c lll_futex_wake ok
2165 @c deallocate_stack dup
2166 @c sched_setaffinity ok
2167 @c tgkill ok
2168 @c sched_setscheduler ok
2169 @c atomic_compare_and_exchange_bool_acq ok
2170 @c nptl_create_event ok
2171 @c lll_unlock (pd->lock) @aculock
2172 @c free @ascuheap @acsmem
2173 @c pthread_attr_destroy ok (cpuset won't be set, so free isn't called)
2174 @c add_request_to_runlist ok
2175 @c pthread_cond_signal ok
2176 @c aio_free_request ok
2177 @c pthread_mutex_unlock @aculock
2178
2179 @c (in the new thread, initiated with clone)
2180 @c start_thread ok
2181 @c HP_TIMING_NOW ok
2182 @c ctype_init @mtslocale
2183 @c atomic_exchange_acq ok
2184 @c lll_futex_wake ok
2185 @c sigemptyset ok
2186 @c sigaddset ok
2187 @c setjmp ok
2188 @c CANCEL_ASYNC -> pthread_enable_asynccancel ok
2189 @c do_cancel ok
2190 @c pthread_unwind ok
2191 @c Unwind_ForcedUnwind or longjmp ok [@ascuheap @acsmem?]
2192 @c lll_lock @asulock @aculock
2193 @c lll_unlock @asulock @aculock
2194 @c CANCEL_RESET -> pthread_disable_asynccancel ok
2195 @c lll_futex_wait ok
2196 @c ->start_routine ok -----
2197 @c call_tls_dtors @asulock @ascuheap @aculock @acsmem
2198 @c user-supplied dtor
2199 @c rtld_lock_lock_recursive (dl_load_lock) @asulock @aculock
2200 @c rtld_lock_unlock_recursive @aculock
2201 @c free @ascuheap @acsmem
2202 @c nptl_deallocate_tsd @ascuheap @acsmem
2203 @c tsd user-supplied dtors ok
2204 @c free @ascuheap @acsmem
2205 @c libc_thread_freeres
2206 @c libc_thread_subfreeres ok
2207 @c atomic_decrement_and_test ok
2208 @c td_eventword ok
2209 @c td_eventmask ok
2210 @c atomic_compare_exchange_bool_acq ok
2211 @c nptl_death_event ok
2212 @c lll_robust_dead ok
2213 @c getpagesize ok
2214 @c madvise ok
2215 @c free_tcb @asulock @ascuheap @aculock @acsmem
2216 @c free @ascuheap @acsmem
2217 @c deallocate_stack @asulock @ascuheap @aculock @acsmem
2218 @c lll_futex_wait ok
2219 @c exit_thread_inline ok
2220 @c syscall(exit) ok
2221
2222 This function initiates an asynchronous read operation. It
2223 immediately returns after the operation was enqueued or when an
2224 error was encountered.
2225
2226 The first @code{aiocbp->aio_nbytes} bytes of the file for which
2227 @code{aiocbp->aio_fildes} is a descriptor are written to the buffer
2228 starting at @code{aiocbp->aio_buf}. Reading starts at the absolute
2229 position @code{aiocbp->aio_offset} in the file.
2230
2231 If prioritized I/O is supported by the platform the
2232 @code{aiocbp->aio_reqprio} value is used to adjust the priority before
2233 the request is actually enqueued.
2234
2235 The calling process is notified about the termination of the read
2236 request according to the @code{aiocbp->aio_sigevent} value.
2237
2238 When @code{aio_read} returns, the return value is zero if no error
2239 occurred that can be found before the process is enqueued. If such an
2240 early error is found, the function returns @math{-1} and sets
2241 @code{errno} to one of the following values:
2242
2243 @table @code
2244 @item EAGAIN
2245 The request was not enqueued due to (temporarily) exceeded resource
2246 limitations.
2247 @item ENOSYS
2248 The @code{aio_read} function is not implemented.
2249 @item EBADF
2250 The @code{aiocbp->aio_fildes} descriptor is not valid. This condition
2251 need not be recognized before enqueueing the request and so this error
2252 might also be signaled asynchronously.
2253 @item EINVAL
2254 The @code{aiocbp->aio_offset} or @code{aiocbp->aio_reqpiro} value is
2255 invalid. This condition need not be recognized before enqueueing the
2256 request and so this error might also be signaled asynchronously.
2257 @end table
2258
2259 If @code{aio_read} returns zero, the current status of the request
2260 can be queried using @code{aio_error} and @code{aio_return} functions.
2261 As long as the value returned by @code{aio_error} is @code{EINPROGRESS}
2262 the operation has not yet completed. If @code{aio_error} returns zero,
2263 the operation successfully terminated, otherwise the value is to be
2264 interpreted as an error code. If the function terminated, the result of
2265 the operation can be obtained using a call to @code{aio_return}. The
2266 returned value is the same as an equivalent call to @code{read} would
2267 have returned. Possible error codes returned by @code{aio_error} are:
2268
2269 @table @code
2270 @item EBADF
2271 The @code{aiocbp->aio_fildes} descriptor is not valid.
2272 @item ECANCELED
2273 The operation was canceled before the operation was finished
2274 (@pxref{Cancel AIO Operations})
2275 @item EINVAL
2276 The @code{aiocbp->aio_offset} value is invalid.
2277 @end table
2278
2279 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2280 function is in fact @code{aio_read64} since the LFS interface transparently
2281 replaces the normal implementation.
2282 @end deftypefun
2283
2284 @comment aio.h
2285 @comment Unix98
2286 @deftypefun int aio_read64 (struct aiocb64 *@var{aiocbp})
2287 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2288 This function is similar to the @code{aio_read} function. The only
2289 difference is that on @w{32 bit} machines, the file descriptor should
2290 be opened in the large file mode. Internally, @code{aio_read64} uses
2291 functionality equivalent to @code{lseek64} (@pxref{File Position
2292 Primitive}) to position the file descriptor correctly for the reading,
2293 as opposed to the @code{lseek} functionality used in @code{aio_read}.
2294
2295 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64}, this
2296 function is available under the name @code{aio_read} and so transparently
2297 replaces the interface for small files on 32 bit machines.
2298 @end deftypefun
2299
2300 To write data asynchronously to a file, there exists an equivalent pair
2301 of functions with a very similar interface.
2302
2303 @comment aio.h
2304 @comment POSIX.1b
2305 @deftypefun int aio_write (struct aiocb *@var{aiocbp})
2306 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2307 This function initiates an asynchronous write operation. The function
2308 call immediately returns after the operation was enqueued or if before
2309 this happens an error was encountered.
2310
2311 The first @code{aiocbp->aio_nbytes} bytes from the buffer starting at
2312 @code{aiocbp->aio_buf} are written to the file for which
2313 @code{aiocbp->aio_fildes} is a descriptor, starting at the absolute
2314 position @code{aiocbp->aio_offset} in the file.
2315
2316 If prioritized I/O is supported by the platform, the
2317 @code{aiocbp->aio_reqprio} value is used to adjust the priority before
2318 the request is actually enqueued.
2319
2320 The calling process is notified about the termination of the read
2321 request according to the @code{aiocbp->aio_sigevent} value.
2322
2323 When @code{aio_write} returns, the return value is zero if no error
2324 occurred that can be found before the process is enqueued. If such an
2325 early error is found the function returns @math{-1} and sets
2326 @code{errno} to one of the following values.
2327
2328 @table @code
2329 @item EAGAIN
2330 The request was not enqueued due to (temporarily) exceeded resource
2331 limitations.
2332 @item ENOSYS
2333 The @code{aio_write} function is not implemented.
2334 @item EBADF
2335 The @code{aiocbp->aio_fildes} descriptor is not valid. This condition
2336 may not be recognized before enqueueing the request, and so this error
2337 might also be signaled asynchronously.
2338 @item EINVAL
2339 The @code{aiocbp->aio_offset} or @code{aiocbp->aio_reqprio} value is
2340 invalid. This condition may not be recognized before enqueueing the
2341 request and so this error might also be signaled asynchronously.
2342 @end table
2343
2344 In the case @code{aio_write} returns zero, the current status of the
2345 request can be queried using the @code{aio_error} and @code{aio_return}
2346 functions. As long as the value returned by @code{aio_error} is
2347 @code{EINPROGRESS} the operation has not yet completed. If
2348 @code{aio_error} returns zero, the operation successfully terminated,
2349 otherwise the value is to be interpreted as an error code. If the
2350 function terminated, the result of the operation can be obtained using a call
2351 to @code{aio_return}. The returned value is the same as an equivalent
2352 call to @code{read} would have returned. Possible error codes returned
2353 by @code{aio_error} are:
2354
2355 @table @code
2356 @item EBADF
2357 The @code{aiocbp->aio_fildes} descriptor is not valid.
2358 @item ECANCELED
2359 The operation was canceled before the operation was finished.
2360 (@pxref{Cancel AIO Operations})
2361 @item EINVAL
2362 The @code{aiocbp->aio_offset} value is invalid.
2363 @end table
2364
2365 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64}, this
2366 function is in fact @code{aio_write64} since the LFS interface transparently
2367 replaces the normal implementation.
2368 @end deftypefun
2369
2370 @comment aio.h
2371 @comment Unix98
2372 @deftypefun int aio_write64 (struct aiocb64 *@var{aiocbp})
2373 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2374 This function is similar to the @code{aio_write} function. The only
2375 difference is that on @w{32 bit} machines the file descriptor should
2376 be opened in the large file mode. Internally @code{aio_write64} uses
2377 functionality equivalent to @code{lseek64} (@pxref{File Position
2378 Primitive}) to position the file descriptor correctly for the writing,
2379 as opposed to the @code{lseek} functionality used in @code{aio_write}.
2380
2381 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64}, this
2382 function is available under the name @code{aio_write} and so transparently
2383 replaces the interface for small files on 32 bit machines.
2384 @end deftypefun
2385
2386 Besides these functions with the more or less traditional interface,
2387 POSIX.1b also defines a function which can initiate more than one
2388 operation at a time, and which can handle freely mixed read and write
2389 operations. It is therefore similar to a combination of @code{readv} and
2390 @code{writev}.
2391
2392 @comment aio.h
2393 @comment POSIX.1b
2394 @deftypefun int lio_listio (int @var{mode}, struct aiocb *const @var{list}[], int @var{nent}, struct sigevent *@var{sig})
2395 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2396 @c Call lio_listio_internal, that takes the aio_requests_mutex lock and
2397 @c enqueues each request. Then, it waits for notification or prepares
2398 @c for it before releasing the lock. Even though it performs memory
2399 @c allocation and locking of its own, it doesn't add any classes of
2400 @c safety issues that aren't already covered by aio_enqueue_request.
2401 The @code{lio_listio} function can be used to enqueue an arbitrary
2402 number of read and write requests at one time. The requests can all be
2403 meant for the same file, all for different files or every solution in
2404 between.
2405
2406 @code{lio_listio} gets the @var{nent} requests from the array pointed to
2407 by @var{list}. The operation to be performed is determined by the
2408 @code{aio_lio_opcode} member in each element of @var{list}. If this
2409 field is @code{LIO_READ} a read operation is enqueued, similar to a call
2410 of @code{aio_read} for this element of the array (except that the way
2411 the termination is signalled is different, as we will see below). If
2412 the @code{aio_lio_opcode} member is @code{LIO_WRITE} a write operation
2413 is enqueued. Otherwise the @code{aio_lio_opcode} must be @code{LIO_NOP}
2414 in which case this element of @var{list} is simply ignored. This
2415 ``operation'' is useful in situations where one has a fixed array of
2416 @code{struct aiocb} elements from which only a few need to be handled at
2417 a time. Another situation is where the @code{lio_listio} call was
2418 canceled before all requests are processed (@pxref{Cancel AIO
2419 Operations}) and the remaining requests have to be reissued.
2420
2421 The other members of each element of the array pointed to by
2422 @code{list} must have values suitable for the operation as described in
2423 the documentation for @code{aio_read} and @code{aio_write} above.
2424
2425 The @var{mode} argument determines how @code{lio_listio} behaves after
2426 having enqueued all the requests. If @var{mode} is @code{LIO_WAIT} it
2427 waits until all requests terminated. Otherwise @var{mode} must be
2428 @code{LIO_NOWAIT} and in this case the function returns immediately after
2429 having enqueued all the requests. In this case the caller gets a
2430 notification of the termination of all requests according to the
2431 @var{sig} parameter. If @var{sig} is @code{NULL} no notification is
2432 sent. Otherwise a signal is sent or a thread is started, just as
2433 described in the description for @code{aio_read} or @code{aio_write}.
2434
2435 If @var{mode} is @code{LIO_WAIT}, the return value of @code{lio_listio}
2436 is @math{0} when all requests completed successfully. Otherwise the
2437 function returns @math{-1} and @code{errno} is set accordingly. To find
2438 out which request or requests failed one has to use the @code{aio_error}
2439 function on all the elements of the array @var{list}.
2440
2441 In case @var{mode} is @code{LIO_NOWAIT}, the function returns @math{0} if
2442 all requests were enqueued correctly. The current state of the requests
2443 can be found using @code{aio_error} and @code{aio_return} as described
2444 above. If @code{lio_listio} returns @math{-1} in this mode, the
2445 global variable @code{errno} is set accordingly. If a request did not
2446 yet terminate, a call to @code{aio_error} returns @code{EINPROGRESS}. If
2447 the value is different, the request is finished and the error value (or
2448 @math{0}) is returned and the result of the operation can be retrieved
2449 using @code{aio_return}.
2450
2451 Possible values for @code{errno} are:
2452
2453 @table @code
2454 @item EAGAIN
2455 The resources necessary to queue all the requests are not available at
2456 the moment. The error status for each element of @var{list} must be
2457 checked to determine which request failed.
2458
2459 Another reason could be that the system wide limit of AIO requests is
2460 exceeded. This cannot be the case for the implementation on @gnusystems{}
2461 since no arbitrary limits exist.
2462 @item EINVAL
2463 The @var{mode} parameter is invalid or @var{nent} is larger than
2464 @code{AIO_LISTIO_MAX}.
2465 @item EIO
2466 One or more of the request's I/O operations failed. The error status of
2467 each request should be checked to determine which one failed.
2468 @item ENOSYS
2469 The @code{lio_listio} function is not supported.
2470 @end table
2471
2472 If the @var{mode} parameter is @code{LIO_NOWAIT} and the caller cancels
2473 a request, the error status for this request returned by
2474 @code{aio_error} is @code{ECANCELED}.
2475
2476 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64}, this
2477 function is in fact @code{lio_listio64} since the LFS interface
2478 transparently replaces the normal implementation.
2479 @end deftypefun
2480
2481 @comment aio.h
2482 @comment Unix98
2483 @deftypefun int lio_listio64 (int @var{mode}, struct aiocb64 *const @var{list}[], int @var{nent}, struct sigevent *@var{sig})
2484 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2485 This function is similar to the @code{lio_listio} function. The only
2486 difference is that on @w{32 bit} machines, the file descriptor should
2487 be opened in the large file mode. Internally, @code{lio_listio64} uses
2488 functionality equivalent to @code{lseek64} (@pxref{File Position
2489 Primitive}) to position the file descriptor correctly for the reading or
2490 writing, as opposed to the @code{lseek} functionality used in
2491 @code{lio_listio}.
2492
2493 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64}, this
2494 function is available under the name @code{lio_listio} and so
2495 transparently replaces the interface for small files on 32 bit
2496 machines.
2497 @end deftypefun
2498
2499 @node Status of AIO Operations
2500 @subsection Getting the Status of AIO Operations
2501
2502 As already described in the documentation of the functions in the last
2503 section, it must be possible to get information about the status of an I/O
2504 request. When the operation is performed truly asynchronously (as with
2505 @code{aio_read} and @code{aio_write} and with @code{lio_listio} when the
2506 mode is @code{LIO_NOWAIT}), one sometimes needs to know whether a
2507 specific request already terminated and if so, what the result was.
2508 The following two functions allow you to get this kind of information.
2509
2510 @comment aio.h
2511 @comment POSIX.1b
2512 @deftypefun int aio_error (const struct aiocb *@var{aiocbp})
2513 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2514 This function determines the error state of the request described by the
2515 @code{struct aiocb} variable pointed to by @var{aiocbp}. If the
2516 request has not yet terminated the value returned is always
2517 @code{EINPROGRESS}. Once the request has terminated the value
2518 @code{aio_error} returns is either @math{0} if the request completed
2519 successfully or it returns the value which would be stored in the
2520 @code{errno} variable if the request would have been done using
2521 @code{read}, @code{write}, or @code{fsync}.
2522
2523 The function can return @code{ENOSYS} if it is not implemented. It
2524 could also return @code{EINVAL} if the @var{aiocbp} parameter does not
2525 refer to an asynchronous operation whose return status is not yet known.
2526
2527 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2528 function is in fact @code{aio_error64} since the LFS interface
2529 transparently replaces the normal implementation.
2530 @end deftypefun
2531
2532 @comment aio.h
2533 @comment Unix98
2534 @deftypefun int aio_error64 (const struct aiocb64 *@var{aiocbp})
2535 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2536 This function is similar to @code{aio_error} with the only difference
2537 that the argument is a reference to a variable of type @code{struct
2538 aiocb64}.
2539
2540 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2541 function is available under the name @code{aio_error} and so
2542 transparently replaces the interface for small files on 32 bit
2543 machines.
2544 @end deftypefun
2545
2546 @comment aio.h
2547 @comment POSIX.1b
2548 @deftypefun ssize_t aio_return (struct aiocb *@var{aiocbp})
2549 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2550 This function can be used to retrieve the return status of the operation
2551 carried out by the request described in the variable pointed to by
2552 @var{aiocbp}. As long as the error status of this request as returned
2553 by @code{aio_error} is @code{EINPROGRESS} the return value of this function is
2554 undefined.
2555
2556 Once the request is finished this function can be used exactly once to
2557 retrieve the return value. Following calls might lead to undefined
2558 behavior. The return value itself is the value which would have been
2559 returned by the @code{read}, @code{write}, or @code{fsync} call.
2560
2561 The function can return @code{ENOSYS} if it is not implemented. It
2562 could also return @code{EINVAL} if the @var{aiocbp} parameter does not
2563 refer to an asynchronous operation whose return status is not yet known.
2564
2565 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2566 function is in fact @code{aio_return64} since the LFS interface
2567 transparently replaces the normal implementation.
2568 @end deftypefun
2569
2570 @comment aio.h
2571 @comment Unix98
2572 @deftypefun ssize_t aio_return64 (struct aiocb64 *@var{aiocbp})
2573 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2574 This function is similar to @code{aio_return} with the only difference
2575 that the argument is a reference to a variable of type @code{struct
2576 aiocb64}.
2577
2578 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2579 function is available under the name @code{aio_return} and so
2580 transparently replaces the interface for small files on 32 bit
2581 machines.
2582 @end deftypefun
2583
2584 @node Synchronizing AIO Operations
2585 @subsection Getting into a Consistent State
2586
2587 When dealing with asynchronous operations it is sometimes necessary to
2588 get into a consistent state. This would mean for AIO that one wants to
2589 know whether a certain request or a group of requests were processed.
2590 This could be done by waiting for the notification sent by the system
2591 after the operation terminated, but this sometimes would mean wasting
2592 resources (mainly computation time). Instead POSIX.1b defines two
2593 functions which will help with most kinds of consistency.
2594
2595 The @code{aio_fsync} and @code{aio_fsync64} functions are only available
2596 if the symbol @code{_POSIX_SYNCHRONIZED_IO} is defined in @file{unistd.h}.
2597
2598 @cindex synchronizing
2599 @comment aio.h
2600 @comment POSIX.1b
2601 @deftypefun int aio_fsync (int @var{op}, struct aiocb *@var{aiocbp})
2602 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2603 @c After fcntl to check that the FD is open, it calls
2604 @c aio_enqueue_request.
2605 Calling this function forces all I/O operations queued at the
2606 time of the function call operating on the file descriptor
2607 @code{aiocbp->aio_fildes} into the synchronized I/O completion state
2608 (@pxref{Synchronizing I/O}). The @code{aio_fsync} function returns
2609 immediately but the notification through the method described in
2610 @code{aiocbp->aio_sigevent} will happen only after all requests for this
2611 file descriptor have terminated and the file is synchronized. This also
2612 means that requests for this very same file descriptor which are queued
2613 after the synchronization request are not affected.
2614
2615 If @var{op} is @code{O_DSYNC} the synchronization happens as with a call
2616 to @code{fdatasync}. Otherwise @var{op} should be @code{O_SYNC} and
2617 the synchronization happens as with @code{fsync}.
2618
2619 As long as the synchronization has not happened, a call to
2620 @code{aio_error} with the reference to the object pointed to by
2621 @var{aiocbp} returns @code{EINPROGRESS}. Once the synchronization is
2622 done @code{aio_error} return @math{0} if the synchronization was not
2623 successful. Otherwise the value returned is the value to which the
2624 @code{fsync} or @code{fdatasync} function would have set the
2625 @code{errno} variable. In this case nothing can be assumed about the
2626 consistency of the data written to this file descriptor.
2627
2628 The return value of this function is @math{0} if the request was
2629 successfully enqueued. Otherwise the return value is @math{-1} and
2630 @code{errno} is set to one of the following values:
2631
2632 @table @code
2633 @item EAGAIN
2634 The request could not be enqueued due to temporary lack of resources.
2635 @item EBADF
2636 The file descriptor @code{@var{aiocbp}->aio_fildes} is not valid.
2637 @item EINVAL
2638 The implementation does not support I/O synchronization or the @var{op}
2639 parameter is other than @code{O_DSYNC} and @code{O_SYNC}.
2640 @item ENOSYS
2641 This function is not implemented.
2642 @end table
2643
2644 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2645 function is in fact @code{aio_fsync64} since the LFS interface
2646 transparently replaces the normal implementation.
2647 @end deftypefun
2648
2649 @comment aio.h
2650 @comment Unix98
2651 @deftypefun int aio_fsync64 (int @var{op}, struct aiocb64 *@var{aiocbp})
2652 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2653 This function is similar to @code{aio_fsync} with the only difference
2654 that the argument is a reference to a variable of type @code{struct
2655 aiocb64}.
2656
2657 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2658 function is available under the name @code{aio_fsync} and so
2659 transparently replaces the interface for small files on 32 bit
2660 machines.
2661 @end deftypefun
2662
2663 Another method of synchronization is to wait until one or more requests of a
2664 specific set terminated. This could be achieved by the @code{aio_*}
2665 functions to notify the initiating process about the termination but in
2666 some situations this is not the ideal solution. In a program which
2667 constantly updates clients somehow connected to the server it is not
2668 always the best solution to go round robin since some connections might
2669 be slow. On the other hand letting the @code{aio_*} functions notify the
2670 caller might also be not the best solution since whenever the process
2671 works on preparing data for a client it makes no sense to be
2672 interrupted by a notification since the new client will not be handled
2673 before the current client is served. For situations like this
2674 @code{aio_suspend} should be used.
2675
2676 @comment aio.h
2677 @comment POSIX.1b
2678 @deftypefun int aio_suspend (const struct aiocb *const @var{list}[], int @var{nent}, const struct timespec *@var{timeout})
2679 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
2680 @c Take aio_requests_mutex, set up waitlist and requestlist, wait
2681 @c for completion or timeout, and release the mutex.
2682 When calling this function, the calling thread is suspended until at
2683 least one of the requests pointed to by the @var{nent} elements of the
2684 array @var{list} has completed. If any of the requests has already
2685 completed at the time @code{aio_suspend} is called, the function returns
2686 immediately. Whether a request has terminated or not is determined by
2687 comparing the error status of the request with @code{EINPROGRESS}. If
2688 an element of @var{list} is @code{NULL}, the entry is simply ignored.
2689
2690 If no request has finished, the calling process is suspended. If
2691 @var{timeout} is @code{NULL}, the process is not woken until a request
2692 has finished. If @var{timeout} is not @code{NULL}, the process remains
2693 suspended at least as long as specified in @var{timeout}. In this case,
2694 @code{aio_suspend} returns with an error.
2695
2696 The return value of the function is @math{0} if one or more requests
2697 from the @var{list} have terminated. Otherwise the function returns
2698 @math{-1} and @code{errno} is set to one of the following values:
2699
2700 @table @code
2701 @item EAGAIN
2702 None of the requests from the @var{list} completed in the time specified
2703 by @var{timeout}.
2704 @item EINTR
2705 A signal interrupted the @code{aio_suspend} function. This signal might
2706 also be sent by the AIO implementation while signalling the termination
2707 of one of the requests.
2708 @item ENOSYS
2709 The @code{aio_suspend} function is not implemented.
2710 @end table
2711
2712 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2713 function is in fact @code{aio_suspend64} since the LFS interface
2714 transparently replaces the normal implementation.
2715 @end deftypefun
2716
2717 @comment aio.h
2718 @comment Unix98
2719 @deftypefun int aio_suspend64 (const struct aiocb64 *const @var{list}[], int @var{nent}, const struct timespec *@var{timeout})
2720 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
2721 This function is similar to @code{aio_suspend} with the only difference
2722 that the argument is a reference to a variable of type @code{struct
2723 aiocb64}.
2724
2725 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2726 function is available under the name @code{aio_suspend} and so
2727 transparently replaces the interface for small files on 32 bit
2728 machines.
2729 @end deftypefun
2730
2731 @node Cancel AIO Operations
2732 @subsection Cancellation of AIO Operations
2733
2734 When one or more requests are asynchronously processed, it might be
2735 useful in some situations to cancel a selected operation, e.g., if it
2736 becomes obvious that the written data is no longer accurate and would
2737 have to be overwritten soon. As an example, assume an application, which
2738 writes data in files in a situation where new incoming data would have
2739 to be written in a file which will be updated by an enqueued request.
2740 The POSIX AIO implementation provides such a function, but this function
2741 is not capable of forcing the cancellation of the request. It is up to the
2742 implementation to decide whether it is possible to cancel the operation
2743 or not. Therefore using this function is merely a hint.
2744
2745 @comment aio.h
2746 @comment POSIX.1b
2747 @deftypefun int aio_cancel (int @var{fildes}, struct aiocb *@var{aiocbp})
2748 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2749 @c After fcntl to check the fd is open, hold aio_requests_mutex, call
2750 @c aio_find_req_fd, aio_remove_request, then aio_notify and
2751 @c aio_free_request each request before releasing the lock.
2752 @c aio_notify calls aio_notify_only and free, besides cond signal or
2753 @c similar. aio_notify_only calls pthread_attr_init,
2754 @c pthread_attr_setdetachstate, malloc, pthread_create,
2755 @c notify_func_wrapper, aio_sigqueue, getpid, raise.
2756 @c notify_func_wraper calls aio_start_notify_thread, free and then the
2757 @c notifier function.
2758 The @code{aio_cancel} function can be used to cancel one or more
2759 outstanding requests. If the @var{aiocbp} parameter is @code{NULL}, the
2760 function tries to cancel all of the outstanding requests which would process
2761 the file descriptor @var{fildes} (i.e., whose @code{aio_fildes} member
2762 is @var{fildes}). If @var{aiocbp} is not @code{NULL}, @code{aio_cancel}
2763 attempts to cancel the specific request pointed to by @var{aiocbp}.
2764
2765 For requests which were successfully canceled, the normal notification
2766 about the termination of the request should take place. I.e., depending
2767 on the @code{struct sigevent} object which controls this, nothing
2768 happens, a signal is sent or a thread is started. If the request cannot
2769 be canceled, it terminates the usual way after performing the operation.
2770
2771 After a request is successfully canceled, a call to @code{aio_error} with
2772 a reference to this request as the parameter will return
2773 @code{ECANCELED} and a call to @code{aio_return} will return @math{-1}.
2774 If the request wasn't canceled and is still running the error status is
2775 still @code{EINPROGRESS}.
2776
2777 The return value of the function is @code{AIO_CANCELED} if there were
2778 requests which haven't terminated and which were successfully canceled.
2779 If there is one or more requests left which couldn't be canceled, the
2780 return value is @code{AIO_NOTCANCELED}. In this case @code{aio_error}
2781 must be used to find out which of the, perhaps multiple, requests (if
2782 @var{aiocbp} is @code{NULL}) weren't successfully canceled. If all
2783 requests already terminated at the time @code{aio_cancel} is called the
2784 return value is @code{AIO_ALLDONE}.
2785
2786 If an error occurred during the execution of @code{aio_cancel} the
2787 function returns @math{-1} and sets @code{errno} to one of the following
2788 values.
2789
2790 @table @code
2791 @item EBADF
2792 The file descriptor @var{fildes} is not valid.
2793 @item ENOSYS
2794 @code{aio_cancel} is not implemented.
2795 @end table
2796
2797 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64}, this
2798 function is in fact @code{aio_cancel64} since the LFS interface
2799 transparently replaces the normal implementation.
2800 @end deftypefun
2801
2802 @comment aio.h
2803 @comment Unix98
2804 @deftypefun int aio_cancel64 (int @var{fildes}, struct aiocb64 *@var{aiocbp})
2805 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{} @ascuheap{}}@acunsafe{@aculock{} @acsmem{}}}
2806 This function is similar to @code{aio_cancel} with the only difference
2807 that the argument is a reference to a variable of type @code{struct
2808 aiocb64}.
2809
2810 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64}, this
2811 function is available under the name @code{aio_cancel} and so
2812 transparently replaces the interface for small files on 32 bit
2813 machines.
2814 @end deftypefun
2815
2816 @node Configuration of AIO
2817 @subsection How to optimize the AIO implementation
2818
2819 The POSIX standard does not specify how the AIO functions are
2820 implemented. They could be system calls, but it is also possible to
2821 emulate them at userlevel.
2822
2823 At the time of writing, the available implementation is a user-level
2824 implementation which uses threads for handling the enqueued requests.
2825 While this implementation requires making some decisions about
2826 limitations, hard limitations are something best avoided
2827 in @theglibc{}. Therefore, @theglibc{} provides a means
2828 for tuning the AIO implementation according to the individual use.
2829
2830 @comment aio.h
2831 @comment GNU
2832 @deftp {Data Type} {struct aioinit}
2833 This data type is used to pass the configuration or tunable parameters
2834 to the implementation. The program has to initialize the members of
2835 this struct and pass it to the implementation using the @code{aio_init}
2836 function.
2837
2838 @table @code
2839 @item int aio_threads
2840 This member specifies the maximal number of threads which may be used
2841 at any one time.
2842 @item int aio_num
2843 This number provides an estimate on the maximal number of simultaneously
2844 enqueued requests.
2845 @item int aio_locks
2846 Unused.
2847 @item int aio_usedba
2848 Unused.
2849 @item int aio_debug
2850 Unused.
2851 @item int aio_numusers
2852 Unused.
2853 @item int aio_reserved[2]
2854 Unused.
2855 @end table
2856 @end deftp
2857
2858 @comment aio.h
2859 @comment GNU
2860 @deftypefun void aio_init (const struct aioinit *@var{init})
2861 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{}}}
2862 @c All changes to global objects are guarded by aio_requests_mutex.
2863 This function must be called before any other AIO function. Calling it
2864 is completely voluntary, as it is only meant to help the AIO
2865 implementation perform better.
2866
2867 Before calling @code{aio_init}, the members of a variable of
2868 type @code{struct aioinit} must be initialized. Then a reference to
2869 this variable is passed as the parameter to @code{aio_init} which itself
2870 may or may not pay attention to the hints.
2871
2872 The function has no return value and no error cases are defined. It is
2873 an extension which follows a proposal from the SGI implementation in
2874 @w{Irix 6}. It is not covered by POSIX.1b or Unix98.
2875 @end deftypefun
2876
2877 @node Control Operations
2878 @section Control Operations on Files
2879
2880 @cindex control operations on files
2881 @cindex @code{fcntl} function
2882 This section describes how you can perform various other operations on
2883 file descriptors, such as inquiring about or setting flags describing
2884 the status of the file descriptor, manipulating record locks, and the
2885 like. All of these operations are performed by the function @code{fcntl}.
2886
2887 The second argument to the @code{fcntl} function is a command that
2888 specifies which operation to perform. The function and macros that name
2889 various flags that are used with it are declared in the header file
2890 @file{fcntl.h}. Many of these flags are also used by the @code{open}
2891 function; see @ref{Opening and Closing Files}.
2892 @pindex fcntl.h
2893
2894 @comment fcntl.h
2895 @comment POSIX.1
2896 @deftypefun int fcntl (int @var{filedes}, int @var{command}, @dots{})
2897 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2898 The @code{fcntl} function performs the operation specified by
2899 @var{command} on the file descriptor @var{filedes}. Some commands
2900 require additional arguments to be supplied. These additional arguments
2901 and the return value and error conditions are given in the detailed
2902 descriptions of the individual commands.
2903
2904 Briefly, here is a list of what the various commands are.
2905
2906 @vtable @code
2907 @item F_DUPFD
2908 Duplicate the file descriptor (return another file descriptor pointing
2909 to the same open file). @xref{Duplicating Descriptors}.
2910
2911 @item F_GETFD
2912 Get flags associated with the file descriptor. @xref{Descriptor Flags}.
2913
2914 @item F_SETFD
2915 Set flags associated with the file descriptor. @xref{Descriptor Flags}.
2916
2917 @item F_GETFL
2918 Get flags associated with the open file. @xref{File Status Flags}.
2919
2920 @item F_SETFL
2921 Set flags associated with the open file. @xref{File Status Flags}.
2922
2923 @item F_GETLK
2924 Test a file lock. @xref{File Locks}.
2925
2926 @item F_SETLK
2927 Set or clear a file lock. @xref{File Locks}.
2928
2929 @item F_SETLKW
2930 Like @code{F_SETLK}, but wait for completion. @xref{File Locks}.
2931
2932 @item F_OFD_GETLK
2933 Test an open file description lock. @xref{Open File Description Locks}.
2934 Specific to Linux.
2935
2936 @item F_OFD_SETLK
2937 Set or clear an open file description lock. @xref{Open File Description Locks}.
2938 Specific to Linux.
2939
2940 @item F_OFD_SETLKW
2941 Like @code{F_OFD_SETLK}, but block until lock is acquired.
2942 @xref{Open File Description Locks}. Specific to Linux.
2943
2944 @item F_GETOWN
2945 Get process or process group ID to receive @code{SIGIO} signals.
2946 @xref{Interrupt Input}.
2947
2948 @item F_SETOWN
2949 Set process or process group ID to receive @code{SIGIO} signals.
2950 @xref{Interrupt Input}.
2951 @end vtable
2952
2953 This function is a cancellation point in multi-threaded programs. This
2954 is a problem if the thread allocates some resources (like memory, file
2955 descriptors, semaphores or whatever) at the time @code{fcntl} is
2956 called. If the thread gets canceled these resources stay allocated
2957 until the program ends. To avoid this calls to @code{fcntl} should be
2958 protected using cancellation handlers.
2959 @c ref pthread_cleanup_push / pthread_cleanup_pop
2960 @end deftypefun
2961
2962
2963 @node Duplicating Descriptors
2964 @section Duplicating Descriptors
2965
2966 @cindex duplicating file descriptors
2967 @cindex redirecting input and output
2968
2969 You can @dfn{duplicate} a file descriptor, or allocate another file
2970 descriptor that refers to the same open file as the original. Duplicate
2971 descriptors share one file position and one set of file status flags
2972 (@pxref{File Status Flags}), but each has its own set of file descriptor
2973 flags (@pxref{Descriptor Flags}).
2974
2975 The major use of duplicating a file descriptor is to implement
2976 @dfn{redirection} of input or output: that is, to change the
2977 file or pipe that a particular file descriptor corresponds to.
2978
2979 You can perform this operation using the @code{fcntl} function with the
2980 @code{F_DUPFD} command, but there are also convenient functions
2981 @code{dup} and @code{dup2} for duplicating descriptors.
2982
2983 @pindex unistd.h
2984 @pindex fcntl.h
2985 The @code{fcntl} function and flags are declared in @file{fcntl.h},
2986 while prototypes for @code{dup} and @code{dup2} are in the header file
2987 @file{unistd.h}.
2988
2989 @comment unistd.h
2990 @comment POSIX.1
2991 @deftypefun int dup (int @var{old})
2992 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2993 This function copies descriptor @var{old} to the first available
2994 descriptor number (the first number not currently open). It is
2995 equivalent to @code{fcntl (@var{old}, F_DUPFD, 0)}.
2996 @end deftypefun
2997
2998 @comment unistd.h
2999 @comment POSIX.1
3000 @deftypefun int dup2 (int @var{old}, int @var{new})
3001 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3002 This function copies the descriptor @var{old} to descriptor number
3003 @var{new}.
3004
3005 If @var{old} is an invalid descriptor, then @code{dup2} does nothing; it
3006 does not close @var{new}. Otherwise, the new duplicate of @var{old}
3007 replaces any previous meaning of descriptor @var{new}, as if @var{new}
3008 were closed first.
3009
3010 If @var{old} and @var{new} are different numbers, and @var{old} is a
3011 valid descriptor number, then @code{dup2} is equivalent to:
3012
3013 @smallexample
3014 close (@var{new});
3015 fcntl (@var{old}, F_DUPFD, @var{new})
3016 @end smallexample
3017
3018 However, @code{dup2} does this atomically; there is no instant in the
3019 middle of calling @code{dup2} at which @var{new} is closed and not yet a
3020 duplicate of @var{old}.
3021 @end deftypefun
3022
3023 @comment fcntl.h
3024 @comment POSIX.1
3025 @deftypevr Macro int F_DUPFD
3026 This macro is used as the @var{command} argument to @code{fcntl}, to
3027 copy the file descriptor given as the first argument.
3028
3029 The form of the call in this case is:
3030
3031 @smallexample
3032 fcntl (@var{old}, F_DUPFD, @var{next-filedes})
3033 @end smallexample
3034
3035 The @var{next-filedes} argument is of type @code{int} and specifies that
3036 the file descriptor returned should be the next available one greater
3037 than or equal to this value.
3038
3039 The return value from @code{fcntl} with this command is normally the value
3040 of the new file descriptor. A return value of @math{-1} indicates an
3041 error. The following @code{errno} error conditions are defined for
3042 this command:
3043
3044 @table @code
3045 @item EBADF
3046 The @var{old} argument is invalid.
3047
3048 @item EINVAL
3049 The @var{next-filedes} argument is invalid.
3050
3051 @item EMFILE
3052 There are no more file descriptors available---your program is already
3053 using the maximum. In BSD and GNU, the maximum is controlled by a
3054 resource limit that can be changed; @pxref{Limits on Resources}, for
3055 more information about the @code{RLIMIT_NOFILE} limit.
3056 @end table
3057
3058 @code{ENFILE} is not a possible error code for @code{dup2} because
3059 @code{dup2} does not create a new opening of a file; duplicate
3060 descriptors do not count toward the limit which @code{ENFILE}
3061 indicates. @code{EMFILE} is possible because it refers to the limit on
3062 distinct descriptor numbers in use in one process.
3063 @end deftypevr
3064
3065 Here is an example showing how to use @code{dup2} to do redirection.
3066 Typically, redirection of the standard streams (like @code{stdin}) is
3067 done by a shell or shell-like program before calling one of the
3068 @code{exec} functions (@pxref{Executing a File}) to execute a new
3069 program in a child process. When the new program is executed, it
3070 creates and initializes the standard streams to point to the
3071 corresponding file descriptors, before its @code{main} function is
3072 invoked.
3073
3074 So, to redirect standard input to a file, the shell could do something
3075 like:
3076
3077 @smallexample
3078 pid = fork ();
3079 if (pid == 0)
3080 @{
3081 char *filename;
3082 char *program;
3083 int file;
3084 @dots{}
3085 file = TEMP_FAILURE_RETRY (open (filename, O_RDONLY));
3086 dup2 (file, STDIN_FILENO);
3087 TEMP_FAILURE_RETRY (close (file));
3088 execv (program, NULL);
3089 @}
3090 @end smallexample
3091
3092 There is also a more detailed example showing how to implement redirection
3093 in the context of a pipeline of processes in @ref{Launching Jobs}.
3094
3095
3096 @node Descriptor Flags
3097 @section File Descriptor Flags
3098 @cindex file descriptor flags
3099
3100 @dfn{File descriptor flags} are miscellaneous attributes of a file
3101 descriptor. These flags are associated with particular file
3102 descriptors, so that if you have created duplicate file descriptors
3103 from a single opening of a file, each descriptor has its own set of flags.
3104
3105 Currently there is just one file descriptor flag: @code{FD_CLOEXEC},
3106 which causes the descriptor to be closed if you use any of the
3107 @code{exec@dots{}} functions (@pxref{Executing a File}).
3108
3109 The symbols in this section are defined in the header file
3110 @file{fcntl.h}.
3111 @pindex fcntl.h
3112
3113 @comment fcntl.h
3114 @comment POSIX.1
3115 @deftypevr Macro int F_GETFD
3116 This macro is used as the @var{command} argument to @code{fcntl}, to
3117 specify that it should return the file descriptor flags associated
3118 with the @var{filedes} argument.
3119
3120 The normal return value from @code{fcntl} with this command is a
3121 nonnegative number which can be interpreted as the bitwise OR of the
3122 individual flags (except that currently there is only one flag to use).
3123
3124 In case of an error, @code{fcntl} returns @math{-1}. The following
3125 @code{errno} error conditions are defined for this command:
3126
3127 @table @code
3128 @item EBADF
3129 The @var{filedes} argument is invalid.
3130 @end table
3131 @end deftypevr
3132
3133
3134 @comment fcntl.h
3135 @comment POSIX.1
3136 @deftypevr Macro int F_SETFD
3137 This macro is used as the @var{command} argument to @code{fcntl}, to
3138 specify that it should set the file descriptor flags associated with the
3139 @var{filedes} argument. This requires a third @code{int} argument to
3140 specify the new flags, so the form of the call is:
3141
3142 @smallexample
3143 fcntl (@var{filedes}, F_SETFD, @var{new-flags})
3144 @end smallexample
3145
3146 The normal return value from @code{fcntl} with this command is an
3147 unspecified value other than @math{-1}, which indicates an error.
3148 The flags and error conditions are the same as for the @code{F_GETFD}
3149 command.
3150 @end deftypevr
3151
3152 The following macro is defined for use as a file descriptor flag with
3153 the @code{fcntl} function. The value is an integer constant usable
3154 as a bit mask value.
3155
3156 @comment fcntl.h
3157 @comment POSIX.1
3158 @deftypevr Macro int FD_CLOEXEC
3159 @cindex close-on-exec (file descriptor flag)
3160 This flag specifies that the file descriptor should be closed when
3161 an @code{exec} function is invoked; see @ref{Executing a File}. When
3162 a file descriptor is allocated (as with @code{open} or @code{dup}),
3163 this bit is initially cleared on the new file descriptor, meaning that
3164 descriptor will survive into the new program after @code{exec}.
3165 @end deftypevr
3166
3167 If you want to modify the file descriptor flags, you should get the
3168 current flags with @code{F_GETFD} and modify the value. Don't assume
3169 that the flags listed here are the only ones that are implemented; your
3170 program may be run years from now and more flags may exist then. For
3171 example, here is a function to set or clear the flag @code{FD_CLOEXEC}
3172 without altering any other flags:
3173
3174 @smallexample
3175 /* @r{Set the @code{FD_CLOEXEC} flag of @var{desc} if @var{value} is nonzero,}
3176 @r{or clear the flag if @var{value} is 0.}
3177 @r{Return 0 on success, or -1 on error with @code{errno} set.} */
3178
3179 int
3180 set_cloexec_flag (int desc, int value)
3181 @{
3182 int oldflags = fcntl (desc, F_GETFD, 0);
3183 /* @r{If reading the flags failed, return error indication now.} */
3184 if (oldflags < 0)
3185 return oldflags;
3186 /* @r{Set just the flag we want to set.} */
3187 if (value != 0)
3188 oldflags |= FD_CLOEXEC;
3189 else
3190 oldflags &= ~FD_CLOEXEC;
3191 /* @r{Store modified flag word in the descriptor.} */
3192 return fcntl (desc, F_SETFD, oldflags);
3193 @}
3194 @end smallexample
3195
3196 @node File Status Flags
3197 @section File Status Flags
3198 @cindex file status flags
3199
3200 @dfn{File status flags} are used to specify attributes of the opening of a
3201 file. Unlike the file descriptor flags discussed in @ref{Descriptor
3202 Flags}, the file status flags are shared by duplicated file descriptors
3203 resulting from a single opening of the file. The file status flags are
3204 specified with the @var{flags} argument to @code{open};
3205 @pxref{Opening and Closing Files}.
3206
3207 File status flags fall into three categories, which are described in the
3208 following sections.
3209
3210 @itemize @bullet
3211 @item
3212 @ref{Access Modes}, specify what type of access is allowed to the
3213 file: reading, writing, or both. They are set by @code{open} and are
3214 returned by @code{fcntl}, but cannot be changed.
3215
3216 @item
3217 @ref{Open-time Flags}, control details of what @code{open} will do.
3218 These flags are not preserved after the @code{open} call.
3219
3220 @item
3221 @ref{Operating Modes}, affect how operations such as @code{read} and
3222 @code{write} are done. They are set by @code{open}, and can be fetched or
3223 changed with @code{fcntl}.
3224 @end itemize
3225
3226 The symbols in this section are defined in the header file
3227 @file{fcntl.h}.
3228 @pindex fcntl.h
3229
3230 @menu
3231 * Access Modes:: Whether the descriptor can read or write.
3232 * Open-time Flags:: Details of @code{open}.
3233 * Operating Modes:: Special modes to control I/O operations.
3234 * Getting File Status Flags:: Fetching and changing these flags.
3235 @end menu
3236
3237 @node Access Modes
3238 @subsection File Access Modes
3239
3240 The file access modes allow a file descriptor to be used for reading,
3241 writing, or both. (On @gnuhurdsystems{}, they can also allow none of these,
3242 and allow execution of the file as a program.) The access modes are chosen
3243 when the file is opened, and never change.
3244
3245 @comment fcntl.h
3246 @comment POSIX.1
3247 @deftypevr Macro int O_RDONLY
3248 Open the file for read access.
3249 @end deftypevr
3250
3251 @comment fcntl.h
3252 @comment POSIX.1
3253 @deftypevr Macro int O_WRONLY
3254 Open the file for write access.
3255 @end deftypevr
3256
3257 @comment fcntl.h
3258 @comment POSIX.1
3259 @deftypevr Macro int O_RDWR
3260 Open the file for both reading and writing.
3261 @end deftypevr
3262
3263 On @gnuhurdsystems{} (and not on other systems), @code{O_RDONLY} and
3264 @code{O_WRONLY} are independent bits that can be bitwise-ORed together,
3265 and it is valid for either bit to be set or clear. This means that
3266 @code{O_RDWR} is the same as @code{O_RDONLY|O_WRONLY}. A file access
3267 mode of zero is permissible; it allows no operations that do input or
3268 output to the file, but does allow other operations such as
3269 @code{fchmod}. On @gnuhurdsystems{}, since ``read-only'' or ``write-only''
3270 is a misnomer, @file{fcntl.h} defines additional names for the file
3271 access modes. These names are preferred when writing GNU-specific code.
3272 But most programs will want to be portable to other POSIX.1 systems and
3273 should use the POSIX.1 names above instead.
3274
3275 @comment fcntl.h (optional)
3276 @comment GNU
3277 @deftypevr Macro int O_READ
3278 Open the file for reading. Same as @code{O_RDONLY}; only defined on GNU.
3279 @end deftypevr
3280
3281 @comment fcntl.h (optional)
3282 @comment GNU
3283 @deftypevr Macro int O_WRITE
3284 Open the file for writing. Same as @code{O_WRONLY}; only defined on GNU.
3285 @end deftypevr
3286
3287 @comment fcntl.h (optional)
3288 @comment GNU
3289 @deftypevr Macro int O_EXEC
3290 Open the file for executing. Only defined on GNU.
3291 @end deftypevr
3292
3293 To determine the file access mode with @code{fcntl}, you must extract
3294 the access mode bits from the retrieved file status flags. On
3295 @gnuhurdsystems{},
3296 you can just test the @code{O_READ} and @code{O_WRITE} bits in
3297 the flags word. But in other POSIX.1 systems, reading and writing
3298 access modes are not stored as distinct bit flags. The portable way to
3299 extract the file access mode bits is with @code{O_ACCMODE}.
3300
3301 @comment fcntl.h
3302 @comment POSIX.1
3303 @deftypevr Macro int O_ACCMODE
3304 This macro stands for a mask that can be bitwise-ANDed with the file
3305 status flag value to produce a value representing the file access mode.
3306 The mode will be @code{O_RDONLY}, @code{O_WRONLY}, or @code{O_RDWR}.
3307 (On @gnuhurdsystems{} it could also be zero, and it never includes the
3308 @code{O_EXEC} bit.)
3309 @end deftypevr
3310
3311 @node Open-time Flags
3312 @subsection Open-time Flags
3313
3314 The open-time flags specify options affecting how @code{open} will behave.
3315 These options are not preserved once the file is open. The exception to
3316 this is @code{O_NONBLOCK}, which is also an I/O operating mode and so it
3317 @emph{is} saved. @xref{Opening and Closing Files}, for how to call
3318 @code{open}.
3319
3320 There are two sorts of options specified by open-time flags.
3321
3322 @itemize @bullet
3323 @item
3324 @dfn{File name translation flags} affect how @code{open} looks up the
3325 file name to locate the file, and whether the file can be created.
3326 @cindex file name translation flags
3327 @cindex flags, file name translation
3328
3329 @item
3330 @dfn{Open-time action flags} specify extra operations that @code{open} will
3331 perform on the file once it is open.
3332 @cindex open-time action flags
3333 @cindex flags, open-time action
3334 @end itemize
3335
3336 Here are the file name translation flags.
3337
3338 @comment fcntl.h
3339 @comment POSIX.1
3340 @deftypevr Macro int O_CREAT
3341 If set, the file will be created if it doesn't already exist.
3342 @c !!! mode arg, umask
3343 @cindex create on open (file status flag)
3344 @end deftypevr
3345
3346 @comment fcntl.h
3347 @comment POSIX.1
3348 @deftypevr Macro int O_EXCL
3349 If both @code{O_CREAT} and @code{O_EXCL} are set, then @code{open} fails
3350 if the specified file already exists. This is guaranteed to never
3351 clobber an existing file.
3352 @end deftypevr
3353
3354 @comment fcntl.h
3355 @comment POSIX.1
3356 @deftypevr Macro int O_NONBLOCK
3357 @cindex non-blocking open
3358 This prevents @code{open} from blocking for a ``long time'' to open the
3359 file. This is only meaningful for some kinds of files, usually devices
3360 such as serial ports; when it is not meaningful, it is harmless and
3361 ignored. Often, opening a port to a modem blocks until the modem reports
3362 carrier detection; if @code{O_NONBLOCK} is specified, @code{open} will
3363 return immediately without a carrier.
3364
3365 Note that the @code{O_NONBLOCK} flag is overloaded as both an I/O operating
3366 mode and a file name translation flag. This means that specifying
3367 @code{O_NONBLOCK} in @code{open} also sets nonblocking I/O mode;
3368 @pxref{Operating Modes}. To open the file without blocking but do normal
3369 I/O that blocks, you must call @code{open} with @code{O_NONBLOCK} set and
3370 then call @code{fcntl} to turn the bit off.
3371 @end deftypevr
3372
3373 @comment fcntl.h
3374 @comment POSIX.1
3375 @deftypevr Macro int O_NOCTTY
3376 If the named file is a terminal device, don't make it the controlling
3377 terminal for the process. @xref{Job Control}, for information about
3378 what it means to be the controlling terminal.
3379
3380 On @gnuhurdsystems{} and 4.4 BSD, opening a file never makes it the
3381 controlling terminal and @code{O_NOCTTY} is zero. However, @gnulinuxsystems{}
3382 and some other systems use a nonzero value for @code{O_NOCTTY} and set the
3383 controlling terminal when you open a file that is a terminal device; so
3384 to be portable, use @code{O_NOCTTY} when it is important to avoid this.
3385 @cindex controlling terminal, setting
3386 @end deftypevr
3387
3388 The following three file name translation flags exist only on
3389 @gnuhurdsystems{}.
3390
3391 @comment fcntl.h (optional)
3392 @comment GNU
3393 @deftypevr Macro int O_IGNORE_CTTY
3394 Do not recognize the named file as the controlling terminal, even if it
3395 refers to the process's existing controlling terminal device. Operations
3396 on the new file descriptor will never induce job control signals.
3397 @xref{Job Control}.
3398 @end deftypevr
3399
3400 @comment fcntl.h (optional)
3401 @comment GNU
3402 @deftypevr Macro int O_NOLINK
3403 If the named file is a symbolic link, open the link itself instead of
3404 the file it refers to. (@code{fstat} on the new file descriptor will
3405 return the information returned by @code{lstat} on the link's name.)
3406 @cindex symbolic link, opening
3407 @end deftypevr
3408
3409 @comment fcntl.h (optional)
3410 @comment GNU
3411 @deftypevr Macro int O_NOTRANS
3412 If the named file is specially translated, do not invoke the translator.
3413 Open the bare file the translator itself sees.
3414 @end deftypevr
3415
3416
3417 The open-time action flags tell @code{open} to do additional operations
3418 which are not really related to opening the file. The reason to do them
3419 as part of @code{open} instead of in separate calls is that @code{open}
3420 can do them @i{atomically}.
3421
3422 @comment fcntl.h
3423 @comment POSIX.1
3424 @deftypevr Macro int O_TRUNC
3425 Truncate the file to zero length. This option is only useful for
3426 regular files, not special files such as directories or FIFOs. POSIX.1
3427 requires that you open the file for writing to use @code{O_TRUNC}. In
3428 BSD and GNU you must have permission to write the file to truncate it,
3429 but you need not open for write access.
3430
3431 This is the only open-time action flag specified by POSIX.1. There is
3432 no good reason for truncation to be done by @code{open}, instead of by
3433 calling @code{ftruncate} afterwards. The @code{O_TRUNC} flag existed in
3434 Unix before @code{ftruncate} was invented, and is retained for backward
3435 compatibility.
3436 @end deftypevr
3437
3438 The remaining operating modes are BSD extensions. They exist only
3439 on some systems. On other systems, these macros are not defined.
3440
3441 @comment fcntl.h (optional)
3442 @comment BSD
3443 @deftypevr Macro int O_SHLOCK
3444 Acquire a shared lock on the file, as with @code{flock}.
3445 @xref{File Locks}.
3446
3447 If @code{O_CREAT} is specified, the locking is done atomically when
3448 creating the file. You are guaranteed that no other process will get
3449 the lock on the new file first.
3450 @end deftypevr
3451
3452 @comment fcntl.h (optional)
3453 @comment BSD
3454 @deftypevr Macro int O_EXLOCK
3455 Acquire an exclusive lock on the file, as with @code{flock}.
3456 @xref{File Locks}. This is atomic like @code{O_SHLOCK}.
3457 @end deftypevr
3458
3459 @node Operating Modes
3460 @subsection I/O Operating Modes
3461
3462 The operating modes affect how input and output operations using a file
3463 descriptor work. These flags are set by @code{open} and can be fetched
3464 and changed with @code{fcntl}.
3465
3466 @comment fcntl.h
3467 @comment POSIX.1
3468 @deftypevr Macro int O_APPEND
3469 The bit that enables append mode for the file. If set, then all
3470 @code{write} operations write the data at the end of the file, extending
3471 it, regardless of the current file position. This is the only reliable
3472 way to append to a file. In append mode, you are guaranteed that the
3473 data you write will always go to the current end of the file, regardless
3474 of other processes writing to the file. Conversely, if you simply set
3475 the file position to the end of file and write, then another process can
3476 extend the file after you set the file position but before you write,
3477 resulting in your data appearing someplace before the real end of file.
3478 @end deftypevr
3479
3480 @comment fcntl.h
3481 @comment POSIX.1
3482 @deftypevr Macro int O_NONBLOCK
3483 The bit that enables nonblocking mode for the file. If this bit is set,
3484 @code{read} requests on the file can return immediately with a failure
3485 status if there is no input immediately available, instead of blocking.
3486 Likewise, @code{write} requests can also return immediately with a
3487 failure status if the output can't be written immediately.
3488
3489 Note that the @code{O_NONBLOCK} flag is overloaded as both an I/O
3490 operating mode and a file name translation flag; @pxref{Open-time Flags}.
3491 @end deftypevr
3492
3493 @comment fcntl.h
3494 @comment BSD
3495 @deftypevr Macro int O_NDELAY
3496 This is an obsolete name for @code{O_NONBLOCK}, provided for
3497 compatibility with BSD. It is not defined by the POSIX.1 standard.
3498 @end deftypevr
3499
3500 The remaining operating modes are BSD and GNU extensions. They exist only
3501 on some systems. On other systems, these macros are not defined.
3502
3503 @comment fcntl.h
3504 @comment BSD
3505 @deftypevr Macro int O_ASYNC
3506 The bit that enables asynchronous input mode. If set, then @code{SIGIO}
3507 signals will be generated when input is available. @xref{Interrupt Input}.
3508
3509 Asynchronous input mode is a BSD feature.
3510 @end deftypevr
3511
3512 @comment fcntl.h
3513 @comment BSD
3514 @deftypevr Macro int O_FSYNC
3515 The bit that enables synchronous writing for the file. If set, each
3516 @code{write} call will make sure the data is reliably stored on disk before
3517 returning. @c !!! xref fsync
3518
3519 Synchronous writing is a BSD feature.
3520 @end deftypevr
3521
3522 @comment fcntl.h
3523 @comment BSD
3524 @deftypevr Macro int O_SYNC
3525 This is another name for @code{O_FSYNC}. They have the same value.
3526 @end deftypevr
3527
3528 @comment fcntl.h
3529 @comment GNU
3530 @deftypevr Macro int O_NOATIME
3531 If this bit is set, @code{read} will not update the access time of the
3532 file. @xref{File Times}. This is used by programs that do backups, so
3533 that backing a file up does not count as reading it.
3534 Only the owner of the file or the superuser may use this bit.
3535
3536 This is a GNU extension.
3537 @end deftypevr
3538
3539 @node Getting File Status Flags
3540 @subsection Getting and Setting File Status Flags
3541
3542 The @code{fcntl} function can fetch or change file status flags.
3543
3544 @comment fcntl.h
3545 @comment POSIX.1
3546 @deftypevr Macro int F_GETFL
3547 This macro is used as the @var{command} argument to @code{fcntl}, to
3548 read the file status flags for the open file with descriptor
3549 @var{filedes}.
3550
3551 The normal return value from @code{fcntl} with this command is a
3552 nonnegative number which can be interpreted as the bitwise OR of the
3553 individual flags. Since the file access modes are not single-bit values,
3554 you can mask off other bits in the returned flags with @code{O_ACCMODE}
3555 to compare them.
3556
3557 In case of an error, @code{fcntl} returns @math{-1}. The following
3558 @code{errno} error conditions are defined for this command:
3559
3560 @table @code
3561 @item EBADF
3562 The @var{filedes} argument is invalid.
3563 @end table
3564 @end deftypevr
3565
3566 @comment fcntl.h
3567 @comment POSIX.1
3568 @deftypevr Macro int F_SETFL
3569 This macro is used as the @var{command} argument to @code{fcntl}, to set
3570 the file status flags for the open file corresponding to the
3571 @var{filedes} argument. This command requires a third @code{int}
3572 argument to specify the new flags, so the call looks like this:
3573
3574 @smallexample
3575 fcntl (@var{filedes}, F_SETFL, @var{new-flags})
3576 @end smallexample
3577
3578 You can't change the access mode for the file in this way; that is,
3579 whether the file descriptor was opened for reading or writing.
3580
3581 The normal return value from @code{fcntl} with this command is an
3582 unspecified value other than @math{-1}, which indicates an error. The
3583 error conditions are the same as for the @code{F_GETFL} command.
3584 @end deftypevr
3585
3586 If you want to modify the file status flags, you should get the current
3587 flags with @code{F_GETFL} and modify the value. Don't assume that the
3588 flags listed here are the only ones that are implemented; your program
3589 may be run years from now and more flags may exist then. For example,
3590 here is a function to set or clear the flag @code{O_NONBLOCK} without
3591 altering any other flags:
3592
3593 @smallexample
3594 @group
3595 /* @r{Set the @code{O_NONBLOCK} flag of @var{desc} if @var{value} is nonzero,}
3596 @r{or clear the flag if @var{value} is 0.}
3597 @r{Return 0 on success, or -1 on error with @code{errno} set.} */
3598
3599 int
3600 set_nonblock_flag (int desc, int value)
3601 @{
3602 int oldflags = fcntl (desc, F_GETFL, 0);
3603 /* @r{If reading the flags failed, return error indication now.} */
3604 if (oldflags == -1)
3605 return -1;
3606 /* @r{Set just the flag we want to set.} */
3607 if (value != 0)
3608 oldflags |= O_NONBLOCK;
3609 else
3610 oldflags &= ~O_NONBLOCK;
3611 /* @r{Store modified flag word in the descriptor.} */
3612 return fcntl (desc, F_SETFL, oldflags);
3613 @}
3614 @end group
3615 @end smallexample
3616
3617 @node File Locks
3618 @section File Locks
3619
3620 @cindex file locks
3621 @cindex record locking
3622 This section describes record locks that are associated with the process.
3623 There is also a different type of record lock that is associated with the
3624 open file description instead of the process. @xref{Open File Description Locks}.
3625
3626 The remaining @code{fcntl} commands are used to support @dfn{record
3627 locking}, which permits multiple cooperating programs to prevent each
3628 other from simultaneously accessing parts of a file in error-prone
3629 ways.
3630
3631 @cindex exclusive lock
3632 @cindex write lock
3633 An @dfn{exclusive} or @dfn{write} lock gives a process exclusive access
3634 for writing to the specified part of the file. While a write lock is in
3635 place, no other process can lock that part of the file.
3636
3637 @cindex shared lock
3638 @cindex read lock
3639 A @dfn{shared} or @dfn{read} lock prohibits any other process from
3640 requesting a write lock on the specified part of the file. However,
3641 other processes can request read locks.
3642
3643 The @code{read} and @code{write} functions do not actually check to see
3644 whether there are any locks in place. If you want to implement a
3645 locking protocol for a file shared by multiple processes, your application
3646 must do explicit @code{fcntl} calls to request and clear locks at the
3647 appropriate points.
3648
3649 Locks are associated with processes. A process can only have one kind
3650 of lock set for each byte of a given file. When any file descriptor for
3651 that file is closed by the process, all of the locks that process holds
3652 on that file are released, even if the locks were made using other
3653 descriptors that remain open. Likewise, locks are released when a
3654 process exits, and are not inherited by child processes created using
3655 @code{fork} (@pxref{Creating a Process}).
3656
3657 When making a lock, use a @code{struct flock} to specify what kind of
3658 lock and where. This data type and the associated macros for the
3659 @code{fcntl} function are declared in the header file @file{fcntl.h}.
3660 @pindex fcntl.h
3661
3662 @comment fcntl.h
3663 @comment POSIX.1
3664 @deftp {Data Type} {struct flock}
3665 This structure is used with the @code{fcntl} function to describe a file
3666 lock. It has these members:
3667
3668 @table @code
3669 @item short int l_type
3670 Specifies the type of the lock; one of @code{F_RDLCK}, @code{F_WRLCK}, or
3671 @code{F_UNLCK}.
3672
3673 @item short int l_whence
3674 This corresponds to the @var{whence} argument to @code{fseek} or
3675 @code{lseek}, and specifies what the offset is relative to. Its value
3676 can be one of @code{SEEK_SET}, @code{SEEK_CUR}, or @code{SEEK_END}.
3677
3678 @item off_t l_start
3679 This specifies the offset of the start of the region to which the lock
3680 applies, and is given in bytes relative to the point specified by the
3681 @code{l_whence} member.
3682
3683 @item off_t l_len
3684 This specifies the length of the region to be locked. A value of
3685 @code{0} is treated specially; it means the region extends to the end of
3686 the file.
3687
3688 @item pid_t l_pid
3689 This field is the process ID (@pxref{Process Creation Concepts}) of the
3690 process holding the lock. It is filled in by calling @code{fcntl} with
3691 the @code{F_GETLK} command, but is ignored when making a lock. If the
3692 conflicting lock is an open file description lock
3693 (@pxref{Open File Description Locks}), then this field will be set to
3694 @math{-1}.
3695 @end table
3696 @end deftp
3697
3698 @comment fcntl.h
3699 @comment POSIX.1
3700 @deftypevr Macro int F_GETLK
3701 This macro is used as the @var{command} argument to @code{fcntl}, to
3702 specify that it should get information about a lock. This command
3703 requires a third argument of type @w{@code{struct flock *}} to be passed
3704 to @code{fcntl}, so that the form of the call is:
3705
3706 @smallexample
3707 fcntl (@var{filedes}, F_GETLK, @var{lockp})
3708 @end smallexample
3709
3710 If there is a lock already in place that would block the lock described
3711 by the @var{lockp} argument, information about that lock overwrites
3712 @code{*@var{lockp}}. Existing locks are not reported if they are
3713 compatible with making a new lock as specified. Thus, you should
3714 specify a lock type of @code{F_WRLCK} if you want to find out about both
3715 read and write locks, or @code{F_RDLCK} if you want to find out about
3716 write locks only.
3717
3718 There might be more than one lock affecting the region specified by the
3719 @var{lockp} argument, but @code{fcntl} only returns information about
3720 one of them. The @code{l_whence} member of the @var{lockp} structure is
3721 set to @code{SEEK_SET} and the @code{l_start} and @code{l_len} fields
3722 set to identify the locked region.
3723
3724 If no lock applies, the only change to the @var{lockp} structure is to
3725 update the @code{l_type} to a value of @code{F_UNLCK}.
3726
3727 The normal return value from @code{fcntl} with this command is an
3728 unspecified value other than @math{-1}, which is reserved to indicate an
3729 error. The following @code{errno} error conditions are defined for
3730 this command:
3731
3732 @table @code
3733 @item EBADF
3734 The @var{filedes} argument is invalid.
3735
3736 @item EINVAL
3737 Either the @var{lockp} argument doesn't specify valid lock information,
3738 or the file associated with @var{filedes} doesn't support locks.
3739 @end table
3740 @end deftypevr
3741
3742 @comment fcntl.h
3743 @comment POSIX.1
3744 @deftypevr Macro int F_SETLK
3745 This macro is used as the @var{command} argument to @code{fcntl}, to
3746 specify that it should set or clear a lock. This command requires a
3747 third argument of type @w{@code{struct flock *}} to be passed to
3748 @code{fcntl}, so that the form of the call is:
3749
3750 @smallexample
3751 fcntl (@var{filedes}, F_SETLK, @var{lockp})
3752 @end smallexample
3753
3754 If the process already has a lock on any part of the region, the old lock
3755 on that part is replaced with the new lock. You can remove a lock
3756 by specifying a lock type of @code{F_UNLCK}.
3757
3758 If the lock cannot be set, @code{fcntl} returns immediately with a value
3759 of @math{-1}. This function does not block while waiting for other processes
3760 to release locks. If @code{fcntl} succeeds, it returns a value other
3761 than @math{-1}.
3762
3763 The following @code{errno} error conditions are defined for this
3764 function:
3765
3766 @table @code
3767 @item EAGAIN
3768 @itemx EACCES
3769 The lock cannot be set because it is blocked by an existing lock on the
3770 file. Some systems use @code{EAGAIN} in this case, and other systems
3771 use @code{EACCES}; your program should treat them alike, after
3772 @code{F_SETLK}. (@gnulinuxhurdsystems{} always use @code{EAGAIN}.)
3773
3774 @item EBADF
3775 Either: the @var{filedes} argument is invalid; you requested a read lock
3776 but the @var{filedes} is not open for read access; or, you requested a
3777 write lock but the @var{filedes} is not open for write access.
3778
3779 @item EINVAL
3780 Either the @var{lockp} argument doesn't specify valid lock information,
3781 or the file associated with @var{filedes} doesn't support locks.
3782
3783 @item ENOLCK
3784 The system has run out of file lock resources; there are already too
3785 many file locks in place.
3786
3787 Well-designed file systems never report this error, because they have no
3788 limitation on the number of locks. However, you must still take account
3789 of the possibility of this error, as it could result from network access
3790 to a file system on another machine.
3791 @end table
3792 @end deftypevr
3793
3794 @comment fcntl.h
3795 @comment POSIX.1
3796 @deftypevr Macro int F_SETLKW
3797 This macro is used as the @var{command} argument to @code{fcntl}, to
3798 specify that it should set or clear a lock. It is just like the
3799 @code{F_SETLK} command, but causes the process to block (or wait)
3800 until the request can be specified.
3801
3802 This command requires a third argument of type @code{struct flock *}, as
3803 for the @code{F_SETLK} command.
3804
3805 The @code{fcntl} return values and errors are the same as for the
3806 @code{F_SETLK} command, but these additional @code{errno} error conditions
3807 are defined for this command:
3808
3809 @table @code
3810 @item EINTR
3811 The function was interrupted by a signal while it was waiting.
3812 @xref{Interrupted Primitives}.
3813
3814 @item EDEADLK
3815 The specified region is being locked by another process. But that
3816 process is waiting to lock a region which the current process has
3817 locked, so waiting for the lock would result in deadlock. The system
3818 does not guarantee that it will detect all such conditions, but it lets
3819 you know if it notices one.
3820 @end table
3821 @end deftypevr
3822
3823
3824 The following macros are defined for use as values for the @code{l_type}
3825 member of the @code{flock} structure. The values are integer constants.
3826
3827 @vtable @code
3828 @comment fcntl.h
3829 @comment POSIX.1
3830 @item F_RDLCK
3831 This macro is used to specify a read (or shared) lock.
3832
3833 @comment fcntl.h
3834 @comment POSIX.1
3835 @item F_WRLCK
3836 This macro is used to specify a write (or exclusive) lock.
3837
3838 @comment fcntl.h
3839 @comment POSIX.1
3840 @item F_UNLCK
3841 This macro is used to specify that the region is unlocked.
3842 @end vtable
3843
3844 As an example of a situation where file locking is useful, consider a
3845 program that can be run simultaneously by several different users, that
3846 logs status information to a common file. One example of such a program
3847 might be a game that uses a file to keep track of high scores. Another
3848 example might be a program that records usage or accounting information
3849 for billing purposes.
3850
3851 Having multiple copies of the program simultaneously writing to the
3852 file could cause the contents of the file to become mixed up. But
3853 you can prevent this kind of problem by setting a write lock on the
3854 file before actually writing to the file.
3855
3856 If the program also needs to read the file and wants to make sure that
3857 the contents of the file are in a consistent state, then it can also use
3858 a read lock. While the read lock is set, no other process can lock
3859 that part of the file for writing.
3860
3861 @c ??? This section could use an example program.
3862
3863 Remember that file locks are only an @emph{advisory} protocol for
3864 controlling access to a file. There is still potential for access to
3865 the file by programs that don't use the lock protocol.
3866
3867 @node Open File Description Locks
3868 @section Open File Description Locks
3869
3870 In contrast to process-associated record locks (@pxref{File Locks}),
3871 open file description record locks are associated with an open file
3872 description rather than a process.
3873
3874 Using @code{fcntl} to apply an open file description lock on a region that
3875 already has an existing open file description lock that was created via the
3876 same file descriptor will never cause a lock conflict.
3877
3878 Open file description locks are also inherited by child processes across
3879 @code{fork}, or @code{clone} with @code{CLONE_FILES} set
3880 (@pxref{Creating a Process}), along with the file descriptor.
3881
3882 It is important to distinguish between the open file @emph{description} (an
3883 instance of an open file, usually created by a call to @code{open}) and
3884 an open file @emph{descriptor}, which is a numeric value that refers to the
3885 open file description. The locks described here are associated with the
3886 open file @emph{description} and not the open file @emph{descriptor}.
3887
3888 Using @code{dup} (@pxref{Duplicating Descriptors}) to copy a file
3889 descriptor does not give you a new open file description, but rather copies a
3890 reference to an existing open file description and assigns it to a new
3891 file descriptor. Thus, open file description locks set on a file
3892 descriptor cloned by @code{dup} will never conflict with open file
3893 description locks set on the original descriptor since they refer to the
3894 same open file description. Depending on the range and type of lock
3895 involved, the original lock may be modified by a @code{F_OFD_SETLK} or
3896 @code{F_OFD_SETLKW} command in this situation however.
3897
3898 Open file description locks always conflict with process-associated locks,
3899 even if acquired by the same process or on the same open file
3900 descriptor.
3901
3902 Open file description locks use the same @code{struct flock} as
3903 process-associated locks as an argument (@pxref{File Locks}) and the
3904 macros for the @code{command} values are also declared in the header file
3905 @file{fcntl.h}. To use them, the macro @code{_GNU_SOURCE} must be
3906 defined prior to including any header file.
3907
3908 In contrast to process-associated locks, any @code{struct flock} used as
3909 an argument to open file description lock commands must have the @code{l_pid}
3910 value set to @math{0}. Also, when returning information about an
3911 open file description lock in a @code{F_GETLK} or @code{F_OFD_GETLK} request,
3912 the @code{l_pid} field in @code{struct flock} will be set to @math{-1}
3913 to indicate that the lock is not associated with a process.
3914
3915 When the same @code{struct flock} is reused as an argument to a
3916 @code{F_OFD_SETLK} or @code{F_OFD_SETLKW} request after being used for an
3917 @code{F_OFD_GETLK} request, it is necessary to inspect and reset the
3918 @code{l_pid} field to @math{0}.
3919
3920 @pindex fcntl.h.
3921
3922 @deftypevr Macro int F_OFD_GETLK
3923 This macro is used as the @var{command} argument to @code{fcntl}, to
3924 specify that it should get information about a lock. This command
3925 requires a third argument of type @w{@code{struct flock *}} to be passed
3926 to @code{fcntl}, so that the form of the call is:
3927
3928 @smallexample
3929 fcntl (@var{filedes}, F_OFD_GETLK, @var{lockp})
3930 @end smallexample
3931
3932 If there is a lock already in place that would block the lock described
3933 by the @var{lockp} argument, information about that lock is written to
3934 @code{*@var{lockp}}. Existing locks are not reported if they are
3935 compatible with making a new lock as specified. Thus, you should
3936 specify a lock type of @code{F_WRLCK} if you want to find out about both
3937 read and write locks, or @code{F_RDLCK} if you want to find out about
3938 write locks only.
3939
3940 There might be more than one lock affecting the region specified by the
3941 @var{lockp} argument, but @code{fcntl} only returns information about
3942 one of them. Which lock is returned in this situation is undefined.
3943
3944 The @code{l_whence} member of the @var{lockp} structure are set to
3945 @code{SEEK_SET} and the @code{l_start} and @code{l_len} fields are set
3946 to identify the locked region.
3947
3948 If no conflicting lock exists, the only change to the @var{lockp} structure
3949 is to update the @code{l_type} field to the value @code{F_UNLCK}.
3950
3951 The normal return value from @code{fcntl} with this command is either @math{0}
3952 on success or @math{-1}, which indicates an error. The following @code{errno}
3953 error conditions are defined for this command:
3954
3955 @table @code
3956 @item EBADF
3957 The @var{filedes} argument is invalid.
3958
3959 @item EINVAL
3960 Either the @var{lockp} argument doesn't specify valid lock information,
3961 the operating system kernel doesn't support open file description locks, or the file
3962 associated with @var{filedes} doesn't support locks.
3963 @end table
3964 @end deftypevr
3965
3966 @comment fcntl.h
3967 @comment POSIX.1
3968 @deftypevr Macro int F_OFD_SETLK
3969 This macro is used as the @var{command} argument to @code{fcntl}, to
3970 specify that it should set or clear a lock. This command requires a
3971 third argument of type @w{@code{struct flock *}} to be passed to
3972 @code{fcntl}, so that the form of the call is:
3973
3974 @smallexample
3975 fcntl (@var{filedes}, F_OFD_SETLK, @var{lockp})
3976 @end smallexample
3977
3978 If the open file already has a lock on any part of the
3979 region, the old lock on that part is replaced with the new lock. You
3980 can remove a lock by specifying a lock type of @code{F_UNLCK}.
3981
3982 If the lock cannot be set, @code{fcntl} returns immediately with a value
3983 of @math{-1}. This command does not wait for other tasks
3984 to release locks. If @code{fcntl} succeeds, it returns @math{0}.
3985
3986 The following @code{errno} error conditions are defined for this
3987 command:
3988
3989 @table @code
3990 @item EAGAIN
3991 The lock cannot be set because it is blocked by an existing lock on the
3992 file.
3993
3994 @item EBADF
3995 Either: the @var{filedes} argument is invalid; you requested a read lock
3996 but the @var{filedes} is not open for read access; or, you requested a
3997 write lock but the @var{filedes} is not open for write access.
3998
3999 @item EINVAL
4000 Either the @var{lockp} argument doesn't specify valid lock information,
4001 the operating system kernel doesn't support open file description locks, or the
4002 file associated with @var{filedes} doesn't support locks.
4003
4004 @item ENOLCK
4005 The system has run out of file lock resources; there are already too
4006 many file locks in place.
4007
4008 Well-designed file systems never report this error, because they have no
4009 limitation on the number of locks. However, you must still take account
4010 of the possibility of this error, as it could result from network access
4011 to a file system on another machine.
4012 @end table
4013 @end deftypevr
4014
4015 @comment fcntl.h
4016 @comment POSIX.1
4017 @deftypevr Macro int F_OFD_SETLKW
4018 This macro is used as the @var{command} argument to @code{fcntl}, to
4019 specify that it should set or clear a lock. It is just like the
4020 @code{F_OFD_SETLK} command, but causes the process to wait until the request
4021 can be completed.
4022
4023 This command requires a third argument of type @code{struct flock *}, as
4024 for the @code{F_OFD_SETLK} command.
4025
4026 The @code{fcntl} return values and errors are the same as for the
4027 @code{F_OFD_SETLK} command, but these additional @code{errno} error conditions
4028 are defined for this command:
4029
4030 @table @code
4031 @item EINTR
4032 The function was interrupted by a signal while it was waiting.
4033 @xref{Interrupted Primitives}.
4034
4035 @end table
4036 @end deftypevr
4037
4038 Open file description locks are useful in the same sorts of situations as
4039 process-associated locks. They can also be used to synchronize file
4040 access between threads within the same process by having each thread perform
4041 its own @code{open} of the file, to obtain its own open file description.
4042
4043 Because open file description locks are automatically freed only upon
4044 closing the last file descriptor that refers to the open file
4045 description, this locking mechanism avoids the possibility that locks
4046 are inadvertently released due to a library routine opening and closing
4047 a file without the application being aware.
4048
4049 As with process-associated locks, open file description locks are advisory.
4050
4051 @node Open File Description Locks Example
4052 @section Open File Description Locks Example
4053
4054 Here is an example of using open file description locks in a threaded
4055 program. If this program used process-associated locks, then it would be
4056 subject to data corruption because process-associated locks are shared
4057 by the threads inside a process, and thus cannot be used by one thread
4058 to lock out another thread in the same process.
4059
4060 Proper error handling has been omitted in the following program for
4061 brevity.
4062
4063 @smallexample
4064 @include ofdlocks.c.texi
4065 @end smallexample
4066
4067 This example creates three threads each of which loops five times,
4068 appending to the file. Access to the file is serialized via open file
4069 description locks. If we compile and run the above program, we'll end up
4070 with /tmp/foo that has 15 lines in it.
4071
4072 If we, however, were to replace the @code{F_OFD_SETLK} and
4073 @code{F_OFD_SETLKW} commands with their process-associated lock
4074 equivalents, the locking essentially becomes a noop since it is all done
4075 within the context of the same process. That leads to data corruption
4076 (typically manifested as missing lines) as some threads race in and
4077 overwrite the data written by others.
4078
4079 @node Interrupt Input
4080 @section Interrupt-Driven Input
4081
4082 @cindex interrupt-driven input
4083 If you set the @code{O_ASYNC} status flag on a file descriptor
4084 (@pxref{File Status Flags}), a @code{SIGIO} signal is sent whenever
4085 input or output becomes possible on that file descriptor. The process
4086 or process group to receive the signal can be selected by using the
4087 @code{F_SETOWN} command to the @code{fcntl} function. If the file
4088 descriptor is a socket, this also selects the recipient of @code{SIGURG}
4089 signals that are delivered when out-of-band data arrives on that socket;
4090 see @ref{Out-of-Band Data}. (@code{SIGURG} is sent in any situation
4091 where @code{select} would report the socket as having an ``exceptional
4092 condition''. @xref{Waiting for I/O}.)
4093
4094 If the file descriptor corresponds to a terminal device, then @code{SIGIO}
4095 signals are sent to the foreground process group of the terminal.
4096 @xref{Job Control}.
4097
4098 @pindex fcntl.h
4099 The symbols in this section are defined in the header file
4100 @file{fcntl.h}.
4101
4102 @comment fcntl.h
4103 @comment BSD
4104 @deftypevr Macro int F_GETOWN
4105 This macro is used as the @var{command} argument to @code{fcntl}, to
4106 specify that it should get information about the process or process
4107 group to which @code{SIGIO} signals are sent. (For a terminal, this is
4108 actually the foreground process group ID, which you can get using
4109 @code{tcgetpgrp}; see @ref{Terminal Access Functions}.)
4110
4111 The return value is interpreted as a process ID; if negative, its
4112 absolute value is the process group ID.
4113
4114 The following @code{errno} error condition is defined for this command:
4115
4116 @table @code
4117 @item EBADF
4118 The @var{filedes} argument is invalid.
4119 @end table
4120 @end deftypevr
4121
4122 @comment fcntl.h
4123 @comment BSD
4124 @deftypevr Macro int F_SETOWN
4125 This macro is used as the @var{command} argument to @code{fcntl}, to
4126 specify that it should set the process or process group to which
4127 @code{SIGIO} signals are sent. This command requires a third argument
4128 of type @code{pid_t} to be passed to @code{fcntl}, so that the form of
4129 the call is:
4130
4131 @smallexample
4132 fcntl (@var{filedes}, F_SETOWN, @var{pid})
4133 @end smallexample
4134
4135 The @var{pid} argument should be a process ID. You can also pass a
4136 negative number whose absolute value is a process group ID.
4137
4138 The return value from @code{fcntl} with this command is @math{-1}
4139 in case of error and some other value if successful. The following
4140 @code{errno} error conditions are defined for this command:
4141
4142 @table @code
4143 @item EBADF
4144 The @var{filedes} argument is invalid.
4145
4146 @item ESRCH
4147 There is no process or process group corresponding to @var{pid}.
4148 @end table
4149 @end deftypevr
4150
4151 @c ??? This section could use an example program.
4152
4153 @node IOCTLs
4154 @section Generic I/O Control operations
4155 @cindex generic i/o control operations
4156 @cindex IOCTLs
4157
4158 @gnusystems{} can handle most input/output operations on many different
4159 devices and objects in terms of a few file primitives - @code{read},
4160 @code{write} and @code{lseek}. However, most devices also have a few
4161 peculiar operations which do not fit into this model. Such as:
4162
4163 @itemize @bullet
4164
4165 @item
4166 Changing the character font used on a terminal.
4167
4168 @item
4169 Telling a magnetic tape system to rewind or fast forward. (Since they
4170 cannot move in byte increments, @code{lseek} is inapplicable).
4171
4172 @item
4173 Ejecting a disk from a drive.
4174
4175 @item
4176 Playing an audio track from a CD-ROM drive.
4177
4178 @item
4179 Maintaining routing tables for a network.
4180
4181 @end itemize
4182
4183 Although some such objects such as sockets and terminals
4184 @footnote{Actually, the terminal-specific functions are implemented with
4185 IOCTLs on many platforms.} have special functions of their own, it would
4186 not be practical to create functions for all these cases.
4187
4188 Instead these minor operations, known as @dfn{IOCTL}s, are assigned code
4189 numbers and multiplexed through the @code{ioctl} function, defined in
4190 @code{sys/ioctl.h}. The code numbers themselves are defined in many
4191 different headers.
4192
4193 @comment sys/ioctl.h
4194 @comment BSD
4195 @deftypefun int ioctl (int @var{filedes}, int @var{command}, @dots{})
4196 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
4197
4198 The @code{ioctl} function performs the generic I/O operation
4199 @var{command} on @var{filedes}.
4200
4201 A third argument is usually present, either a single number or a pointer
4202 to a structure. The meaning of this argument, the returned value, and
4203 any error codes depends upon the command used. Often @math{-1} is
4204 returned for a failure.
4205
4206 @end deftypefun
4207
4208 On some systems, IOCTLs used by different devices share the same numbers.
4209 Thus, although use of an inappropriate IOCTL @emph{usually} only produces
4210 an error, you should not attempt to use device-specific IOCTLs on an
4211 unknown device.
4212
4213 Most IOCTLs are OS-specific and/or only used in special system utilities,
4214 and are thus beyond the scope of this document. For an example of the use
4215 of an IOCTL, see @ref{Out-of-Band Data}.
4216
4217 @c FIXME this is undocumented:
4218 @c dup3