Update.
[platform/upstream/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 * Truncating Files::                    Change the size of a file.
37 * I/O Primitives::                      Reading and writing data.
38 * File Position Primitive::             Setting a descriptor's file
39                                          position.
40 * Descriptors and Streams::             Converting descriptor to stream
41                                          or vice-versa.
42 * Stream/Descriptor Precautions::       Precautions needed if you use both
43                                          descriptors and streams.
44 * Waiting for I/O::                     How to check for input or output
45                                          on multiple file descriptors.
46 * Synchronizing I/O::                   Making sure all I/O actions completed.
47 * Asynchronous I/O::                    Perform I/O in parallel.
48 * Control Operations::                  Various other operations on file
49                                          descriptors.
50 * Duplicating Descriptors::             Fcntl commands for duplicating
51                                          file descriptors.
52 * Descriptor Flags::                    Fcntl commands for manipulating
53                                          flags associated with file
54                                          descriptors.
55 * File Status Flags::                   Fcntl commands for manipulating
56                                          flags associated with open files.
57 * File Locks::                          Fcntl commands for implementing
58                                          file locking.
59 * Interrupt Input::                     Getting an asynchronous signal when
60                                          input arrives.
61 @end menu
62
63
64 @node Opening and Closing Files
65 @section Opening and Closing Files
66
67 @cindex opening a file descriptor
68 @cindex closing a file descriptor
69 This section describes the primitives for opening and closing files
70 using file descriptors.  The @code{open} and @code{creat} functions are
71 declared in the header file @file{fcntl.h}, while @code{close} is
72 declared in @file{unistd.h}.
73 @pindex unistd.h
74 @pindex fcntl.h
75
76 @comment fcntl.h
77 @comment POSIX.1
78 @deftypefun int open (const char *@var{filename}, int @var{flags}[, mode_t @var{mode}])
79 The @code{open} function creates and returns a new file descriptor
80 for the file named by @var{filename}.  Initially, the file position
81 indicator for the file is at the beginning of the file.  The argument
82 @var{mode} is used only when a file is created, but it doesn't hurt
83 to supply the argument in any case.
84
85 The @var{flags} argument controls how the file is to be opened.  This is
86 a bit mask; you create the value by the bitwise OR of the appropriate
87 parameters (using the @samp{|} operator in C).
88 @xref{File Status Flags}, for the parameters available.
89
90 The normal return value from @code{open} is a non-negative integer file
91 descriptor.  In the case of an error, a value of @code{-1} is returned
92 instead.  In addition to the usual file name errors (@pxref{File
93 Name Errors}), the following @code{errno} error conditions are defined
94 for this function:
95
96 @table @code
97 @item EACCES
98 The file exists but is not readable/writable as requested by the @var{flags}
99 argument, the file does not exist and the directory is unwritable so
100 it cannot be created.
101
102 @item EEXIST
103 Both @code{O_CREAT} and @code{O_EXCL} are set, and the named file already
104 exists.
105
106 @item EINTR
107 The @code{open} operation was interrupted by a signal.
108 @xref{Interrupted Primitives}.
109
110 @item EISDIR
111 The @var{flags} argument specified write access, and the file is a directory.
112
113 @item EMFILE
114 The process has too many files open.
115 The maximum number of file descriptors is controlled by the
116 @code{RLIMIT_NOFILE} resource limit; @pxref{Limits on Resources}.
117
118 @item ENFILE
119 The entire system, or perhaps the file system which contains the
120 directory, cannot support any additional open files at the moment.
121 (This problem cannot happen on the GNU system.)
122
123 @item ENOENT
124 The named file does not exist, and @code{O_CREAT} is not specified.
125
126 @item ENOSPC
127 The directory or file system that would contain the new file cannot be
128 extended, because there is no disk space left.
129
130 @item ENXIO
131 @code{O_NONBLOCK} and @code{O_WRONLY} are both set in the @var{flags}
132 argument, the file named by @var{filename} is a FIFO (@pxref{Pipes and
133 FIFOs}), and no process has the file open for reading.
134
135 @item EROFS
136 The file resides on a read-only file system and any of @w{@code{O_WRONLY}},
137 @code{O_RDWR}, and @code{O_TRUNC} are set in the @var{flags} argument,
138 or @code{O_CREAT} is set and the file does not already exist.
139 @end table
140
141 @c !!! umask
142
143 If on a 32 bits machine the sources are translated with
144 @code{_FILE_OFFSET_BITS == 64} the function @code{open} returns a file
145 descriptor opened in the large file mode which enables the file handling
146 functions to use files up to @math{2^63} bytes in size and offset from
147 @math{-2^63} to @math{2^63}.  This happens transparently for the user
148 since all of the lowlevel file handling functions are equally replaced.
149
150 This function is a cancelation point in multi-threaded programs.  This
151 is a problem if the thread allocates some resources (like memory, file
152 descriptors, semaphores or whatever) at the time @code{open} is
153 called.  If the thread gets canceled these resources stay allocated
154 until the program ends.  To avoid this calls to @code{open} should be
155 protected using cancelation handlers.
156 @c ref pthread_cleanup_push / pthread_cleanup_pop
157
158 The @code{open} function is the underlying primitive for the @code{fopen}
159 and @code{freopen} functions, that create streams.
160 @end deftypefun
161
162 @comment fcntl.h
163 @comment Unix98
164 @deftypefun int open64 (const char *@var{filename}, int @var{flags}[, mode_t @var{mode}])
165 This function is similar to @code{open}.  It returns a file descriptor
166 which can be used to access the file named by @var{filename}.  The only
167 the difference is that on 32 bits systems the file is opened in the
168 large file mode.  I.e., file length and file offsets can exceed 31 bits.
169
170 When the sources are translated with @code{_FILE_OFFSET_BITS == 64} this
171 function is actually available under the name @code{open}.  I.e., the
172 new, extended API using 64 bit file sizes and offsets transparently
173 replaces the old API.
174 @end deftypefun
175
176 @comment fcntl.h
177 @comment POSIX.1
178 @deftypefn {Obsolete function} int creat (const char *@var{filename}, mode_t @var{mode})
179 This function is obsolete.  The call:
180
181 @smallexample
182 creat (@var{filename}, @var{mode})
183 @end smallexample
184
185 @noindent
186 is equivalent to:
187
188 @smallexample
189 open (@var{filename}, O_WRONLY | O_CREAT | O_TRUNC, @var{mode})
190 @end smallexample
191
192 If on a 32 bits machine the sources are translated with
193 @code{_FILE_OFFSET_BITS == 64} the function @code{creat} returns a file
194 descriptor opened in the large file mode which enables the file handling
195 functions to use files up to @math{2^63} in size and offset from
196 @math{-2^63} to @math{2^63}.  This happens transparently for the user
197 since all of the lowlevel file handling functions are equally replaced.
198 @end deftypefn
199
200 @comment fcntl.h
201 @comment Unix98
202 @deftypefn {Obsolete function} int creat64 (const char *@var{filename}, mode_t @var{mode})
203 This function is similar to @code{creat}.  It returns a file descriptor
204 which can be used to access the file named by @var{filename}.  The only
205 the difference is that on 32 bits systems the file is opened in the
206 large file mode.  I.e., file length and file offsets can exceed 31 bits.
207
208 To use this file descriptor one must not use the normal operations but
209 instead the counterparts named @code{*64}, e.g., @code{read64}.
210
211 When the sources are translated with @code{_FILE_OFFSET_BITS == 64} this
212 function is actually available under the name @code{open}.  I.e., the
213 new, extended API using 64 bit file sizes and offsets transparently
214 replaces the old API.
215 @end deftypefn
216
217 @comment unistd.h
218 @comment POSIX.1
219 @deftypefun int close (int @var{filedes})
220 The function @code{close} closes the file descriptor @var{filedes}.
221 Closing a file has the following consequences:
222
223 @itemize @bullet
224 @item
225 The file descriptor is deallocated.
226
227 @item
228 Any record locks owned by the process on the file are unlocked.
229
230 @item
231 When all file descriptors associated with a pipe or FIFO have been closed,
232 any unread data is discarded.
233 @end itemize
234
235 This function is a cancelation point in multi-threaded programs.  This
236 is a problem if the thread allocates some resources (like memory, file
237 descriptors, semaphores or whatever) at the time @code{close} is
238 called.  If the thread gets canceled these resources stay allocated
239 until the program ends.  To avoid this calls to @code{close} should be
240 protected using cancelation handlers.
241 @c ref pthread_cleanup_push / pthread_cleanup_pop
242
243 The normal return value from @code{close} is @code{0}; a value of @code{-1}
244 is returned in case of failure.  The following @code{errno} error
245 conditions are defined for this function:
246
247 @table @code
248 @item EBADF
249 The @var{filedes} argument is not a valid file descriptor.
250
251 @item EINTR
252 The @code{close} call was interrupted by a signal.
253 @xref{Interrupted Primitives}.
254 Here is an example of how to handle @code{EINTR} properly:
255
256 @smallexample
257 TEMP_FAILURE_RETRY (close (desc));
258 @end smallexample
259
260 @item ENOSPC
261 @itemx EIO
262 @itemx EDQUOT
263 When the file is accessed by NFS, these errors from @code{write} can sometimes
264 not be detected until @code{close}.  @xref{I/O Primitives}, for details
265 on their meaning.
266 @end table
267
268 Please note that there is @emph{no} separate @code{close64} function.
269 This is not necessary since this function does not determine nor depend
270 on the mode of the file.  The kernel which performs the @code{close}
271 operation knows for which mode the descriptor is used and can handle
272 this situation.
273 @end deftypefun
274
275 To close a stream, call @code{fclose} (@pxref{Closing Streams}) instead
276 of trying to close its underlying file descriptor with @code{close}.
277 This flushes any buffered output and updates the stream object to
278 indicate that it is closed.
279
280
281 @node Truncating Files
282 @section Change the size of a file
283
284 In some situations it is useful to explicitly determine the size of a
285 file.  Since the 4.2BSD days there is a function to truncate a file to
286 at most a given number of bytes and POSIX defines one additional
287 function.  The prototypes for these functions are in @file{unistd.h}.
288
289 @comment unistd.h
290 @comment X/Open
291 @deftypefun int truncate (const char *@var{name}, off_t @var{length})
292 The @code{truncation} function truncates the file named by @var{name} to
293 at most @var{length} bytes.  I.e., if the file was larger before the
294 extra bytes are stripped of.  If the file was small or equal to
295 @var{length} in size before nothing is done.  The file must be writable
296 by the user to perform this operation.
297
298 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
299 @code{truncate} function is in fact @code{truncate64} and the type
300 @code{off_t} has 64 bits which makes it possible to handle files up to
301 @math{2^63} bytes in length.
302
303 The return value is zero is everything went ok.  Otherwise the return
304 value is @math{-1} and the global variable @var{errno} is set to:
305 @table @code
306 @item EACCES
307 The file is not accessible to the user.
308 @item EINVAL
309 The @var{length} value is illegal.
310 @item EISDIR
311 The object named by @var{name} is a directory.
312 @item ENOENT
313 The file named by @var{name} does not exist.
314 @item ENOTDIR
315 One part of the @var{name} is not a directory.
316 @end table
317
318 This function was introduced in 4.2BSD but also was available in later
319 @w{System V} systems.  It is not added to POSIX since the authors felt
320 it is only of marginally additional utility.  See below.
321 @end deftypefun
322
323 @comment unistd.h
324 @comment Unix98
325 @deftypefun int truncate64 (const char *@var{name}, off64_t @var{length})
326 This function is similar to the @code{truncate} function.  The
327 difference is that the @var{length} argument is 64 bits wide even on 32
328 bits machines which allows to handle file with a size up to @math{2^63}
329 bytes.
330
331 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
332 32 bits machine this function is actually available under the name
333 @code{truncate} and so transparently replaces the 32 bits interface.
334 @end deftypefun
335
336 @comment unistd.h
337 @comment POSIX
338 @deftypefun int ftruncate (int @var{fd}, off_t @var{length})
339 The @code{ftruncate} function is similar to the @code{truncate}
340 function.  The main difference is that it takes a descriptor for an
341 opened file instead of a file name to identify the object.  The file
342 must be opened for writing to successfully carry out the operation.
343
344 The POSIX standard leaves it implementation defined what happens if the
345 specified new @var{length} of the file is bigger than the original size.
346 The @code{ftruncate} function might simply leave the file alone and do
347 nothing or it can increase the size to the desired size.  In this later
348 case the extended area should be zero-filled.  So using @code{ftruncate}
349 is no reliable way to increase the file size but if it is possible it is
350 probably the fastest way.  The function also operates on POSIX shared
351 memory segments if these are implemented by the system.
352
353 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
354 @code{ftruncate} function is in fact @code{ftruncate64} and the type
355 @code{off_t} has 64 bits which makes it possible to handle files up to
356 @math{2^63} bytes in length.
357
358 On success the function returns zero.  Otherwise it returns @math{-1}
359 and set @var{errno} to one of these values:
360 @table @code
361 @item EBADF
362 @var{fd} is no valid file descriptor or is not opened for writing.
363 @item EINVAL
364 The object referred to by @var{fd} does not permit this operation.
365 @item EROFS
366 The file is on a read-only file system.
367 @end table
368 @end deftypefun
369
370 @comment unistd.h
371 @comment Unix98
372 @deftypefun int ftruncate64 (int @var{id}, off64_t @var{length})
373 This function is similar to the @code{ftruncate} function.  The
374 difference is that the @var{length} argument is 64 bits wide even on 32
375 bits machines which allows to handle file with a size up to @math{2^63}
376 bytes.
377
378 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
379 32 bits machine this function is actually available under the name
380 @code{ftruncate} and so transparently replaces the 32 bits interface.
381 @end deftypefun
382
383 @node I/O Primitives
384 @section Input and Output Primitives
385
386 This section describes the functions for performing primitive input and
387 output operations on file descriptors: @code{read}, @code{write}, and
388 @code{lseek}.  These functions are declared in the header file
389 @file{unistd.h}.
390 @pindex unistd.h
391
392 @comment unistd.h
393 @comment POSIX.1
394 @deftp {Data Type} ssize_t
395 This data type is used to represent the sizes of blocks that can be
396 read or written in a single operation.  It is similar to @code{size_t},
397 but must be a signed type.
398 @end deftp
399
400 @cindex reading from a file descriptor
401 @comment unistd.h
402 @comment POSIX.1
403 @deftypefun ssize_t read (int @var{filedes}, void *@var{buffer}, size_t @var{size})
404 The @code{read} function reads up to @var{size} bytes from the file
405 with descriptor @var{filedes}, storing the results in the @var{buffer}.
406 (This is not necessarily a character string and there is no terminating
407 null character added.)
408
409 @cindex end-of-file, on a file descriptor
410 The return value is the number of bytes actually read.  This might be
411 less than @var{size}; for example, if there aren't that many bytes left
412 in the file or if there aren't that many bytes immediately available.
413 The exact behavior depends on what kind of file it is.  Note that
414 reading less than @var{size} bytes is not an error.
415
416 A value of zero indicates end-of-file (except if the value of the
417 @var{size} argument is also zero).  This is not considered an error.
418 If you keep calling @code{read} while at end-of-file, it will keep
419 returning zero and doing nothing else.
420
421 If @code{read} returns at least one character, there is no way you can
422 tell whether end-of-file was reached.  But if you did reach the end, the
423 next read will return zero.
424
425 In case of an error, @code{read} returns @code{-1}.  The following
426 @code{errno} error conditions are defined for this function:
427
428 @table @code
429 @item EAGAIN
430 Normally, when no input is immediately available, @code{read} waits for
431 some input.  But if the @code{O_NONBLOCK} flag is set for the file
432 (@pxref{File Status Flags}), @code{read} returns immediately without
433 reading any data, and reports this error.
434
435 @strong{Compatibility Note:} Most versions of BSD Unix use a different
436 error code for this: @code{EWOULDBLOCK}.  In the GNU library,
437 @code{EWOULDBLOCK} is an alias for @code{EAGAIN}, so it doesn't matter
438 which name you use.
439
440 On some systems, reading a large amount of data from a character special
441 file can also fail with @code{EAGAIN} if the kernel cannot find enough
442 physical memory to lock down the user's pages.  This is limited to
443 devices that transfer with direct memory access into the user's memory,
444 which means it does not include terminals, since they always use
445 separate buffers inside the kernel.  This problem never happens in the
446 GNU system.
447
448 Any condition that could result in @code{EAGAIN} can instead result in a
449 successful @code{read} which returns fewer bytes than requested.
450 Calling @code{read} again immediately would result in @code{EAGAIN}.
451
452 @item EBADF
453 The @var{filedes} argument is not a valid file descriptor,
454 or is not open for reading.
455
456 @item EINTR
457 @code{read} was interrupted by a signal while it was waiting for input.
458 @xref{Interrupted Primitives}.  A signal will not necessary cause
459 @code{read} to return @code{EINTR}; it may instead result in a
460 successful @code{read} which returns fewer bytes than requested.
461
462 @item EIO
463 For many devices, and for disk files, this error code indicates
464 a hardware error.
465
466 @code{EIO} also occurs when a background process tries to read from the
467 controlling terminal, and the normal action of stopping the process by
468 sending it a @code{SIGTTIN} signal isn't working.  This might happen if
469 signal is being blocked or ignored, or because the process group is
470 orphaned.  @xref{Job Control}, for more information about job control,
471 and @ref{Signal Handling}, for information about signals.
472 @end table
473
474 Please note that there is no function named @code{read64}.  This is not
475 necessary since this function does not directly modify or handle the
476 possibly wide file offset.  Since the kernel handles this state
477 internally the @code{read} function can be used for all cases.
478
479 This function is a cancelation point in multi-threaded programs.  This
480 is a problem if the thread allocates some resources (like memory, file
481 descriptors, semaphores or whatever) at the time @code{read} is
482 called.  If the thread gets canceled these resources stay allocated
483 until the program ends.  To avoid this calls to @code{read} should be
484 protected using cancelation handlers.
485 @c ref pthread_cleanup_push / pthread_cleanup_pop
486
487 The @code{read} function is the underlying primitive for all of the
488 functions that read from streams, such as @code{fgetc}.
489 @end deftypefun
490
491 @comment unistd.h
492 @comment Unix98
493 @deftypefun ssize_t pread (int @var{filedes}, void *@var{buffer}, size_t @var{size}, off_t @var{offset})
494 The @code{pread} function is similar to the @code{read} function.  The
495 first three arguments are identical and also the return values and error
496 codes correspond.
497
498 The difference is the fourth argument and its handling.  The data block
499 is not read from the current position of the file descriptor
500 @code{filedes}.  Instead the data is read from the file starting at
501 position @var{offset}.  The position of the file descriptor itself is
502 not effected by the operation.  The value is the same as before the call.
503
504 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
505 @code{pread} function is in fact @code{pread64} and the type
506 @code{off_t} has 64 bits which makes it possible to handle files up to
507 @math{2^63} bytes in length.
508
509 The return value of @code{pread} describes the number of bytes read.
510 In the error case it returns @math{-1} like @code{read} does and the
511 error codes are also the same.  Only there are a few more error codes:
512 @table @code
513 @item EINVAL
514 The value given for @var{offset} is negative and therefore illegal.
515
516 @item ESPIPE
517 The file descriptor @var{filedes} is associate with a pipe or a FIFO and
518 this device does not allow positioning of the file pointer.
519 @end table
520
521 The function is an extension defined in the Unix Single Specification
522 version 2.
523 @end deftypefun
524
525 @comment unistd.h
526 @comment Unix98
527 @deftypefun ssize_t pread64 (int @var{filedes}, void *@var{buffer}, size_t @var{size}, off64_t @var{offset})
528 This function is similar to the @code{pread} function.  The difference
529 is that the @var{offset} parameter is of type @code{off64_t} instead of
530 @code{off_t} which makes it possible on 32 bits machines to address
531 files larger than @math{2^31} bytes and up to @math{2^63} bytes.  The
532 file descriptor @code{filedes} must be opened using @code{open64} since
533 otherwise the large offsets possible with @code{off64_t} will lead to
534 errors with a descriptor in small file mode.
535
536 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
537 32 bits machine this function is actually available under the name
538 @code{pread} and so transparently replaces the 32 bits interface.
539 @end deftypefun
540
541 @cindex writing to a file descriptor
542 @comment unistd.h
543 @comment POSIX.1
544 @deftypefun ssize_t write (int @var{filedes}, const void *@var{buffer}, size_t @var{size})
545 The @code{write} function writes up to @var{size} bytes from
546 @var{buffer} to the file with descriptor @var{filedes}.  The data in
547 @var{buffer} is not necessarily a character string and a null character is
548 output like any other character.
549
550 The return value is the number of bytes actually written.  This may be
551 @var{size}, but can always be smaller.  Your program should always call
552 @code{write} in a loop, iterating until all the data is written.
553
554 Once @code{write} returns, the data is enqueued to be written and can be
555 read back right away, but it is not necessarily written out to permanent
556 storage immediately.  You can use @code{fsync} when you need to be sure
557 your data has been permanently stored before continuing.  (It is more
558 efficient for the system to batch up consecutive writes and do them all
559 at once when convenient.  Normally they will always be written to disk
560 within a minute or less.)  Modern systems provide another function
561 @code{fdatasync} which guarantees integrity only for the file data and
562 is therefore faster.
563 @c !!! xref fsync, fdatasync
564 You can use the @code{O_FSYNC} open mode to make @code{write} always
565 store the data to disk before returning; @pxref{Operating Modes}.
566
567 In the case of an error, @code{write} returns @code{-1}.  The following
568 @code{errno} error conditions are defined for this function:
569
570 @table @code
571 @item EAGAIN
572 Normally, @code{write} blocks until the write operation is complete.
573 But if the @code{O_NONBLOCK} flag is set for the file (@pxref{Control
574 Operations}), it returns immediately without writing any data, and
575 reports this error.  An example of a situation that might cause the
576 process to block on output is writing to a terminal device that supports
577 flow control, where output has been suspended by receipt of a STOP
578 character.
579
580 @strong{Compatibility Note:} Most versions of BSD Unix use a different
581 error code for this: @code{EWOULDBLOCK}.  In the GNU library,
582 @code{EWOULDBLOCK} is an alias for @code{EAGAIN}, so it doesn't matter
583 which name you use.
584
585 On some systems, writing a large amount of data from a character special
586 file can also fail with @code{EAGAIN} if the kernel cannot find enough
587 physical memory to lock down the user's pages.  This is limited to
588 devices that transfer with direct memory access into the user's memory,
589 which means it does not include terminals, since they always use
590 separate buffers inside the kernel.  This problem does not arise in the
591 GNU system.
592
593 @item EBADF
594 The @var{filedes} argument is not a valid file descriptor,
595 or is not open for writing.
596
597 @item EFBIG
598 The size of the file would become larger than the implementation can support.
599
600 @item EINTR
601 The @code{write} operation was interrupted by a signal while it was
602 blocked waiting for completion.  A signal will not necessary cause
603 @code{write} to return @code{EINTR}; it may instead result in a
604 successful @code{write} which writes fewer bytes than requested.
605 @xref{Interrupted Primitives}.
606
607 @item EIO
608 For many devices, and for disk files, this error code indicates
609 a hardware error.
610
611 @item ENOSPC
612 The device containing the file is full.
613
614 @item EPIPE
615 This error is returned when you try to write to a pipe or FIFO that
616 isn't open for reading by any process.  When this happens, a @code{SIGPIPE}
617 signal is also sent to the process; see @ref{Signal Handling}.
618 @end table
619
620 Unless you have arranged to prevent @code{EINTR} failures, you should
621 check @code{errno} after each failing call to @code{write}, and if the
622 error was @code{EINTR}, you should simply repeat the call.
623 @xref{Interrupted Primitives}.  The easy way to do this is with the
624 macro @code{TEMP_FAILURE_RETRY}, as follows:
625
626 @smallexample
627 nbytes = TEMP_FAILURE_RETRY (write (desc, buffer, count));
628 @end smallexample
629
630 Please note that there is no function named @code{write64}.  This is not
631 necessary since this function does not directly modify or handle the
632 possibly wide file offset.  Since the kernel handles this state
633 internally the @code{write} function can be used for all cases.
634
635 This function is a cancelation point in multi-threaded programs.  This
636 is a problem if the thread allocates some resources (like memory, file
637 descriptors, semaphores or whatever) at the time @code{write} is
638 called.  If the thread gets canceled these resources stay allocated
639 until the program ends.  To avoid this calls to @code{write} should be
640 protected using cancelation handlers.
641 @c ref pthread_cleanup_push / pthread_cleanup_pop
642
643 The @code{write} function is the underlying primitive for all of the
644 functions that write to streams, such as @code{fputc}.
645 @end deftypefun
646
647 @comment unistd.h
648 @comment Unix98
649 @deftypefun ssize_t pwrite (int @var{filedes}, const void *@var{buffer}, size_t @var{size}, off_t @var{offset})
650 The @code{pwrite} function is similar to the @code{write} function.  The
651 first three arguments are identical and also the return values and error
652 codes correspond.
653
654 The difference is the fourth argument and its handling.  The data block
655 is not written to the current position of the file descriptor
656 @code{filedes}.  Instead the data is written to the file starting at
657 position @var{offset}.  The position of the file descriptor itself is
658 not effected by the operation.  The value is the same as before the call.
659
660 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
661 @code{pwrite} function is in fact @code{pwrite64} and the type
662 @code{off_t} has 64 bits which makes it possible to handle files up to
663 @math{2^63} bytes in length.
664
665 The return value of @code{pwrite} describes the number of written bytes.
666 In the error case it returns @math{-1} like @code{write} does and the
667 error codes are also the same.  Only there are a few more error codes:
668 @table @code
669 @item EINVAL
670 The value given for @var{offset} is negative and therefore illegal.
671
672 @item ESPIPE
673 The file descriptor @var{filedes} is associate with a pipe or a FIFO and
674 this device does not allow positioning of the file pointer.
675 @end table
676
677 The function is an extension defined in the Unix Single Specification
678 version 2.
679 @end deftypefun
680
681 @comment unistd.h
682 @comment Unix98
683 @deftypefun ssize_t pwrite64 (int @var{filedes}, const void *@var{buffer}, size_t @var{size}, off64_t @var{offset})
684 This function is similar to the @code{pwrite} function.  The difference
685 is that the @var{offset} parameter is of type @code{off64_t} instead of
686 @code{off_t} which makes it possible on 32 bits machines to address
687 files larger than @math{2^31} bytes and up to @math{2^63} bytes.  The
688 file descriptor @code{filedes} must be opened using @code{open64} since
689 otherwise the large offsets possible with @code{off64_t} will lead to
690 errors with a descriptor in small file mode.
691
692 When the source file is compiled using @code{_FILE_OFFSET_BITS == 64} on a
693 32 bits machine this function is actually available under the name
694 @code{pwrite} and so transparently replaces the 32 bits interface.
695 @end deftypefun
696
697
698 @node File Position Primitive
699 @section Setting the File Position of a Descriptor
700
701 Just as you can set the file position of a stream with @code{fseek}, you
702 can set the file position of a descriptor with @code{lseek}.  This
703 specifies the position in the file for the next @code{read} or
704 @code{write} operation.  @xref{File Positioning}, for more information
705 on the file position and what it means.
706
707 To read the current file position value from a descriptor, use
708 @code{lseek (@var{desc}, 0, SEEK_CUR)}.
709
710 @cindex file positioning on a file descriptor
711 @cindex positioning a file descriptor
712 @cindex seeking on a file descriptor
713 @comment unistd.h
714 @comment POSIX.1
715 @deftypefun off_t lseek (int @var{filedes}, off_t @var{offset}, int @var{whence})
716 The @code{lseek} function is used to change the file position of the
717 file with descriptor @var{filedes}.
718
719 The @var{whence} argument specifies how the @var{offset} should be
720 interpreted in the same way as for the @code{fseek} function, and must be
721 one of the symbolic constants @code{SEEK_SET}, @code{SEEK_CUR}, or
722 @code{SEEK_END}.
723
724 @table @code
725 @item SEEK_SET
726 Specifies that @var{whence} is a count of characters from the beginning
727 of the file.
728
729 @item SEEK_CUR
730 Specifies that @var{whence} is a count of characters from the current
731 file position.  This count may be positive or negative.
732
733 @item SEEK_END
734 Specifies that @var{whence} is a count of characters from the end of
735 the file.  A negative count specifies a position within the current
736 extent of the file; a positive count specifies a position past the
737 current end.  If you set the position past the current end, and
738 actually write data, you will extend the file with zeros up to that
739 position.@end table
740
741 The return value from @code{lseek} is normally the resulting file
742 position, measured in bytes from the beginning of the file.
743 You can use this feature together with @code{SEEK_CUR} to read the
744 current file position.
745
746 If you want to append to the file, setting the file position to the
747 current end of file with @code{SEEK_END} is not sufficient.  Another
748 process may write more data after you seek but before you write,
749 extending the file so the position you write onto clobbers their data.
750 Instead, use the @code{O_APPEND} operating mode; @pxref{Operating Modes}.
751
752 You can set the file position past the current end of the file.  This
753 does not by itself make the file longer; @code{lseek} never changes the
754 file.  But subsequent output at that position will extend the file.
755 Characters between the previous end of file and the new position are
756 filled with zeros.  Extending the file in this way can create a
757 ``hole'': the blocks of zeros are not actually allocated on disk, so the
758 file takes up less space than it appears so; it is then called a
759 ``sparse file''.
760 @cindex sparse files
761 @cindex holes in files
762
763 If the file position cannot be changed, or the operation is in some way
764 invalid, @code{lseek} returns a value of @code{-1}.  The following
765 @code{errno} error conditions are defined for this function:
766
767 @table @code
768 @item EBADF
769 The @var{filedes} is not a valid file descriptor.
770
771 @item EINVAL
772 The @var{whence} argument value is not valid, or the resulting
773 file offset is not valid.  A file offset is invalid.
774
775 @item ESPIPE
776 The @var{filedes} corresponds to an object that cannot be positioned,
777 such as a pipe, FIFO or terminal device.  (POSIX.1 specifies this error
778 only for pipes and FIFOs, but in the GNU system, you always get
779 @code{ESPIPE} if the object is not seekable.)
780 @end table
781
782 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
783 @code{lseek} function is in fact @code{lseek64} and the type
784 @code{off_t} has 64 bits which makes it possible to handle files up to
785 @math{2^63} bytes in length.
786
787 This function is a cancelation point in multi-threaded programs.  This
788 is a problem if the thread allocates some resources (like memory, file
789 descriptors, semaphores or whatever) at the time @code{lseek} is
790 called.  If the thread gets canceled these resources stay allocated
791 until the program ends.  To avoid this calls to @code{lseek} should be
792 protected using cancelation handlers.
793 @c ref pthread_cleanup_push / pthread_cleanup_pop
794
795 The @code{lseek} function is the underlying primitive for the
796 @code{fseek}, @code{fseeko}, @code{ftell}, @code{ftello} and
797 @code{rewind} functions, which operate on streams instead of file
798 descriptors.
799 @end deftypefun
800
801 @comment unistd.h
802 @comment Unix98
803 @deftypefun off64_t lseek64 (int @var{filedes}, off64_t @var{offset}, int @var{whence})
804 This function is similar to the @code{lseek} function.  The difference
805 is that the @var{offset} parameter is of type @code{off64_t} instead of
806 @code{off_t} which makes it possible on 32 bits machines to address
807 files larger than @math{2^31} bytes and up to @math{2^63} bytes.  The
808 file descriptor @code{filedes} must be opened using @code{open64} since
809 otherwise the large offsets possible with @code{off64_t} will lead to
810 errors with a descriptor in small file mode.
811
812 When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} on a
813 32 bits machine this function is actually available under the name
814 @code{lseek} and so transparently replaces the 32 bits interface.
815 @end deftypefun
816
817 You can have multiple descriptors for the same file if you open the file
818 more than once, or if you duplicate a descriptor with @code{dup}.
819 Descriptors that come from separate calls to @code{open} have independent
820 file positions; using @code{lseek} on one descriptor has no effect on the
821 other.  For example,
822
823 @smallexample
824 @group
825 @{
826   int d1, d2;
827   char buf[4];
828   d1 = open ("foo", O_RDONLY);
829   d2 = open ("foo", O_RDONLY);
830   lseek (d1, 1024, SEEK_SET);
831   read (d2, buf, 4);
832 @}
833 @end group
834 @end smallexample
835
836 @noindent
837 will read the first four characters of the file @file{foo}.  (The
838 error-checking code necessary for a real program has been omitted here
839 for brevity.)
840
841 By contrast, descriptors made by duplication share a common file
842 position with the original descriptor that was duplicated.  Anything
843 which alters the file position of one of the duplicates, including
844 reading or writing data, affects all of them alike.  Thus, for example,
845
846 @smallexample
847 @{
848   int d1, d2, d3;
849   char buf1[4], buf2[4];
850   d1 = open ("foo", O_RDONLY);
851   d2 = dup (d1);
852   d3 = dup (d2);
853   lseek (d3, 1024, SEEK_SET);
854   read (d1, buf1, 4);
855   read (d2, buf2, 4);
856 @}
857 @end smallexample
858
859 @noindent
860 will read four characters starting with the 1024'th character of
861 @file{foo}, and then four more characters starting with the 1028'th
862 character.
863
864 @comment sys/types.h
865 @comment POSIX.1
866 @deftp {Data Type} off_t
867 This is an arithmetic data type used to represent file sizes.
868 In the GNU system, this is equivalent to @code{fpos_t} or @code{long int}.
869
870 If the source is compiled with @code{_FILE_OFFSET_BITS == 64} this type
871 is transparently replaced by @code{off64_t}.
872 @end deftp
873
874 @comment sys/types.h
875 @comment Unix98
876 @deftp {Data Type} off64_t
877 This type is used similar to @code{off_t}.  The difference is that even
878 on 32 bits machines, where the @code{off_t} type would have 32 bits,
879 @code{off64_t} has 64 bits and so is able to address files up to
880 @math{2^63} bytes in length.
881
882 When compiling with @code{_FILE_OFFSET_BITS == 64} this type is
883 available under the name @code{off_t}.
884 @end deftp
885
886 These aliases for the @samp{SEEK_@dots{}} constants exist for the sake
887 of compatibility with older BSD systems.  They are defined in two
888 different header files: @file{fcntl.h} and @file{sys/file.h}.
889
890 @table @code
891 @item L_SET
892 An alias for @code{SEEK_SET}.
893
894 @item L_INCR
895 An alias for @code{SEEK_CUR}.
896
897 @item L_XTND
898 An alias for @code{SEEK_END}.
899 @end table
900
901 @node Descriptors and Streams
902 @section Descriptors and Streams
903 @cindex streams, and file descriptors
904 @cindex converting file descriptor to stream
905 @cindex extracting file descriptor from stream
906
907 Given an open file descriptor, you can create a stream for it with the
908 @code{fdopen} function.  You can get the underlying file descriptor for
909 an existing stream with the @code{fileno} function.  These functions are
910 declared in the header file @file{stdio.h}.
911 @pindex stdio.h
912
913 @comment stdio.h
914 @comment POSIX.1
915 @deftypefun {FILE *} fdopen (int @var{filedes}, const char *@var{opentype})
916 The @code{fdopen} function returns a new stream for the file descriptor
917 @var{filedes}.
918
919 The @var{opentype} argument is interpreted in the same way as for the
920 @code{fopen} function (@pxref{Opening Streams}), except that
921 the @samp{b} option is not permitted; this is because GNU makes no
922 distinction between text and binary files.  Also, @code{"w"} and
923 @code{"w+"} do not cause truncation of the file; these have affect only
924 when opening a file, and in this case the file has already been opened.
925 You must make sure that the @var{opentype} argument matches the actual
926 mode of the open file descriptor.
927
928 The return value is the new stream.  If the stream cannot be created
929 (for example, if the modes for the file indicated by the file descriptor
930 do not permit the access specified by the @var{opentype} argument), a
931 null pointer is returned instead.
932
933 In some other systems, @code{fdopen} may fail to detect that the modes
934 for file descriptor do not permit the access specified by
935 @code{opentype}.  The GNU C library always checks for this.
936 @end deftypefun
937
938 For an example showing the use of the @code{fdopen} function,
939 see @ref{Creating a Pipe}.
940
941 @comment stdio.h
942 @comment POSIX.1
943 @deftypefun int fileno (FILE *@var{stream})
944 This function returns the file descriptor associated with the stream
945 @var{stream}.  If an error is detected (for example, if the @var{stream}
946 is not valid) or if @var{stream} does not do I/O to a file,
947 @code{fileno} returns @code{-1}.
948 @end deftypefun
949
950 @cindex standard file descriptors
951 @cindex file descriptors, standard
952 There are also symbolic constants defined in @file{unistd.h} for the
953 file descriptors belonging to the standard streams @code{stdin},
954 @code{stdout}, and @code{stderr}; see @ref{Standard Streams}.
955 @pindex unistd.h
956
957 @comment unistd.h
958 @comment POSIX.1
959 @table @code
960 @item STDIN_FILENO
961 @vindex STDIN_FILENO
962 This macro has value @code{0}, which is the file descriptor for
963 standard input.
964 @cindex standard input file descriptor
965
966 @comment unistd.h
967 @comment POSIX.1
968 @item STDOUT_FILENO
969 @vindex STDOUT_FILENO
970 This macro has value @code{1}, which is the file descriptor for
971 standard output.
972 @cindex standard output file descriptor
973
974 @comment unistd.h
975 @comment POSIX.1
976 @item STDERR_FILENO
977 @vindex STDERR_FILENO
978 This macro has value @code{2}, which is the file descriptor for
979 standard error output.
980 @end table
981 @cindex standard error file descriptor
982
983 @node Stream/Descriptor Precautions
984 @section Dangers of Mixing Streams and Descriptors
985 @cindex channels
986 @cindex streams and descriptors
987 @cindex descriptors and streams
988 @cindex mixing descriptors and streams
989
990 You can have multiple file descriptors and streams (let's call both
991 streams and descriptors ``channels'' for short) connected to the same
992 file, but you must take care to avoid confusion between channels.  There
993 are two cases to consider: @dfn{linked} channels that share a single
994 file position value, and @dfn{independent} channels that have their own
995 file positions.
996
997 It's best to use just one channel in your program for actual data
998 transfer to any given file, except when all the access is for input.
999 For example, if you open a pipe (something you can only do at the file
1000 descriptor level), either do all I/O with the descriptor, or construct a
1001 stream from the descriptor with @code{fdopen} and then do all I/O with
1002 the stream.
1003
1004 @menu
1005 * Linked Channels::        Dealing with channels sharing a file position.
1006 * Independent Channels::   Dealing with separately opened, unlinked channels.
1007 * Cleaning Streams::       Cleaning a stream makes it safe to use
1008                             another channel.
1009 @end menu
1010
1011 @node Linked Channels
1012 @subsection Linked Channels
1013 @cindex linked channels
1014
1015 Channels that come from a single opening share the same file position;
1016 we call them @dfn{linked} channels.  Linked channels result when you
1017 make a stream from a descriptor using @code{fdopen}, when you get a
1018 descriptor from a stream with @code{fileno}, when you copy a descriptor
1019 with @code{dup} or @code{dup2}, and when descriptors are inherited
1020 during @code{fork}.  For files that don't support random access, such as
1021 terminals and pipes, @emph{all} channels are effectively linked.  On
1022 random-access files, all append-type output streams are effectively
1023 linked to each other.
1024
1025 @cindex cleaning up a stream
1026 If you have been using a stream for I/O, and you want to do I/O using
1027 another channel (either a stream or a descriptor) that is linked to it,
1028 you must first @dfn{clean up} the stream that you have been using.
1029 @xref{Cleaning Streams}.
1030
1031 Terminating a process, or executing a new program in the process,
1032 destroys all the streams in the process.  If descriptors linked to these
1033 streams persist in other processes, their file positions become
1034 undefined as a result.  To prevent this, you must clean up the streams
1035 before destroying them.
1036
1037 @node Independent Channels
1038 @subsection Independent Channels
1039 @cindex independent channels
1040
1041 When you open channels (streams or descriptors) separately on a seekable
1042 file, each channel has its own file position.  These are called
1043 @dfn{independent channels}.
1044
1045 The system handles each channel independently.  Most of the time, this
1046 is quite predictable and natural (especially for input): each channel
1047 can read or write sequentially at its own place in the file.  However,
1048 if some of the channels are streams, you must take these precautions:
1049
1050 @itemize @bullet
1051 @item
1052 You should clean an output stream after use, before doing anything else
1053 that might read or write from the same part of the file.
1054
1055 @item
1056 You should clean an input stream before reading data that may have been
1057 modified using an independent channel.  Otherwise, you might read
1058 obsolete data that had been in the stream's buffer.
1059 @end itemize
1060
1061 If you do output to one channel at the end of the file, this will
1062 certainly leave the other independent channels positioned somewhere
1063 before the new end.  You cannot reliably set their file positions to the
1064 new end of file before writing, because the file can always be extended
1065 by another process between when you set the file position and when you
1066 write the data.  Instead, use an append-type descriptor or stream; they
1067 always output at the current end of the file.  In order to make the
1068 end-of-file position accurate, you must clean the output channel you
1069 were using, if it is a stream.
1070
1071 It's impossible for two channels to have separate file pointers for a
1072 file that doesn't support random access.  Thus, channels for reading or
1073 writing such files are always linked, never independent.  Append-type
1074 channels are also always linked.  For these channels, follow the rules
1075 for linked channels; see @ref{Linked Channels}.
1076
1077 @node Cleaning Streams
1078 @subsection Cleaning Streams
1079
1080 On the GNU system, you can clean up any stream with @code{fclean}:
1081
1082 @comment stdio.h
1083 @comment GNU
1084 @deftypefun int fclean (FILE *@var{stream})
1085 Clean up the stream @var{stream} so that its buffer is empty.  If
1086 @var{stream} is doing output, force it out.  If @var{stream} is doing
1087 input, give the data in the buffer back to the system, arranging to
1088 reread it.
1089 @end deftypefun
1090
1091 On other systems, you can use @code{fflush} to clean a stream in most
1092 cases.
1093
1094 You can skip the @code{fclean} or @code{fflush} if you know the stream
1095 is already clean.  A stream is clean whenever its buffer is empty.  For
1096 example, an unbuffered stream is always clean.  An input stream that is
1097 at end-of-file is clean.  A line-buffered stream is clean when the last
1098 character output was a newline.
1099
1100 There is one case in which cleaning a stream is impossible on most
1101 systems.  This is when the stream is doing input from a file that is not
1102 random-access.  Such streams typically read ahead, and when the file is
1103 not random access, there is no way to give back the excess data already
1104 read.  When an input stream reads from a random-access file,
1105 @code{fflush} does clean the stream, but leaves the file pointer at an
1106 unpredictable place; you must set the file pointer before doing any
1107 further I/O.  On the GNU system, using @code{fclean} avoids both of
1108 these problems.
1109
1110 Closing an output-only stream also does @code{fflush}, so this is a
1111 valid way of cleaning an output stream.  On the GNU system, closing an
1112 input stream does @code{fclean}.
1113
1114 You need not clean a stream before using its descriptor for control
1115 operations such as setting terminal modes; these operations don't affect
1116 the file position and are not affected by it.  You can use any
1117 descriptor for these operations, and all channels are affected
1118 simultaneously.  However, text already ``output'' to a stream but still
1119 buffered by the stream will be subject to the new terminal modes when
1120 subsequently flushed.  To make sure ``past'' output is covered by the
1121 terminal settings that were in effect at the time, flush the output
1122 streams for that terminal before setting the modes.  @xref{Terminal
1123 Modes}.
1124
1125 @node Waiting for I/O
1126 @section Waiting for Input or Output
1127 @cindex waiting for input or output
1128 @cindex multiplexing input
1129 @cindex input from multiple files
1130
1131 Sometimes a program needs to accept input on multiple input channels
1132 whenever input arrives.  For example, some workstations may have devices
1133 such as a digitizing tablet, function button box, or dial box that are
1134 connected via normal asynchronous serial interfaces; good user interface
1135 style requires responding immediately to input on any device.  Another
1136 example is a program that acts as a server to several other processes
1137 via pipes or sockets.
1138
1139 You cannot normally use @code{read} for this purpose, because this
1140 blocks the program until input is available on one particular file
1141 descriptor; input on other channels won't wake it up.  You could set
1142 nonblocking mode and poll each file descriptor in turn, but this is very
1143 inefficient.
1144
1145 A better solution is to use the @code{select} function.  This blocks the
1146 program until input or output is ready on a specified set of file
1147 descriptors, or until a timer expires, whichever comes first.  This
1148 facility is declared in the header file @file{sys/types.h}.
1149 @pindex sys/types.h
1150
1151 In the case of a server socket (@pxref{Listening}), we say that
1152 ``input'' is available when there are pending connections that could be
1153 accepted (@pxref{Accepting Connections}).  @code{accept} for server
1154 sockets blocks and interacts with @code{select} just as @code{read} does
1155 for normal input.
1156
1157 @cindex file descriptor sets, for @code{select}
1158 The file descriptor sets for the @code{select} function are specified
1159 as @code{fd_set} objects.  Here is the description of the data type
1160 and some macros for manipulating these objects.
1161
1162 @comment sys/types.h
1163 @comment BSD
1164 @deftp {Data Type} fd_set
1165 The @code{fd_set} data type represents file descriptor sets for the
1166 @code{select} function.  It is actually a bit array.
1167 @end deftp
1168
1169 @comment sys/types.h
1170 @comment BSD
1171 @deftypevr Macro int FD_SETSIZE
1172 The value of this macro is the maximum number of file descriptors that a
1173 @code{fd_set} object can hold information about.  On systems with a
1174 fixed maximum number, @code{FD_SETSIZE} is at least that number.  On
1175 some systems, including GNU, there is no absolute limit on the number of
1176 descriptors open, but this macro still has a constant value which
1177 controls the number of bits in an @code{fd_set}; if you get a file
1178 descriptor with a value as high as @code{FD_SETSIZE}, you cannot put
1179 that descriptor into an @code{fd_set}.
1180 @end deftypevr
1181
1182 @comment sys/types.h
1183 @comment BSD
1184 @deftypefn Macro void FD_ZERO (fd_set *@var{set})
1185 This macro initializes the file descriptor set @var{set} to be the
1186 empty set.
1187 @end deftypefn
1188
1189 @comment sys/types.h
1190 @comment BSD
1191 @deftypefn Macro void FD_SET (int @var{filedes}, fd_set *@var{set})
1192 This macro adds @var{filedes} to the file descriptor set @var{set}.
1193 @end deftypefn
1194
1195 @comment sys/types.h
1196 @comment BSD
1197 @deftypefn Macro void FD_CLR (int @var{filedes}, fd_set *@var{set})
1198 This macro removes @var{filedes} from the file descriptor set @var{set}.
1199 @end deftypefn
1200
1201 @comment sys/types.h
1202 @comment BSD
1203 @deftypefn Macro int FD_ISSET (int @var{filedes}, fd_set *@var{set})
1204 This macro returns a nonzero value (true) if @var{filedes} is a member
1205 of the file descriptor set @var{set}, and zero (false) otherwise.
1206 @end deftypefn
1207
1208 Next, here is the description of the @code{select} function itself.
1209
1210 @comment sys/types.h
1211 @comment BSD
1212 @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})
1213 The @code{select} function blocks the calling process until there is
1214 activity on any of the specified sets of file descriptors, or until the
1215 timeout period has expired.
1216
1217 The file descriptors specified by the @var{read-fds} argument are
1218 checked to see if they are ready for reading; the @var{write-fds} file
1219 descriptors are checked to see if they are ready for writing; and the
1220 @var{except-fds} file descriptors are checked for exceptional
1221 conditions.  You can pass a null pointer for any of these arguments if
1222 you are not interested in checking for that kind of condition.
1223
1224 A file descriptor is considered ready for reading if it is at end of
1225 file.  A server socket is considered ready for reading if there is a
1226 pending connection which can be accepted with @code{accept};
1227 @pxref{Accepting Connections}.  A client socket is ready for writing when
1228 its connection is fully established; @pxref{Connecting}.
1229
1230 ``Exceptional conditions'' does not mean errors---errors are reported
1231 immediately when an erroneous system call is executed, and do not
1232 constitute a state of the descriptor.  Rather, they include conditions
1233 such as the presence of an urgent message on a socket.  (@xref{Sockets},
1234 for information on urgent messages.)
1235
1236 The @code{select} function checks only the first @var{nfds} file
1237 descriptors.  The usual thing is to pass @code{FD_SETSIZE} as the value
1238 of this argument.
1239
1240 The @var{timeout} specifies the maximum time to wait.  If you pass a
1241 null pointer for this argument, it means to block indefinitely until one
1242 of the file descriptors is ready.  Otherwise, you should provide the
1243 time in @code{struct timeval} format; see @ref{High-Resolution
1244 Calendar}.  Specify zero as the time (a @code{struct timeval} containing
1245 all zeros) if you want to find out which descriptors are ready without
1246 waiting if none are ready.
1247
1248 The normal return value from @code{select} is the total number of ready file
1249 descriptors in all of the sets.  Each of the argument sets is overwritten
1250 with information about the descriptors that are ready for the corresponding
1251 operation.  Thus, to see if a particular descriptor @var{desc} has input,
1252 use @code{FD_ISSET (@var{desc}, @var{read-fds})} after @code{select} returns.
1253
1254 If @code{select} returns because the timeout period expires, it returns
1255 a value of zero.
1256
1257 Any signal will cause @code{select} to return immediately.  So if your
1258 program uses signals, you can't rely on @code{select} to keep waiting
1259 for the full time specified.  If you want to be sure of waiting for a
1260 particular amount of time, you must check for @code{EINTR} and repeat
1261 the @code{select} with a newly calculated timeout based on the current
1262 time.  See the example below.  See also @ref{Interrupted Primitives}.
1263
1264 If an error occurs, @code{select} returns @code{-1} and does not modify
1265 the argument file descriptor sets.  The following @code{errno} error
1266 conditions are defined for this function:
1267
1268 @table @code
1269 @item EBADF
1270 One of the file descriptor sets specified an invalid file descriptor.
1271
1272 @item EINTR
1273 The operation was interrupted by a signal.  @xref{Interrupted Primitives}.
1274
1275 @item EINVAL
1276 The @var{timeout} argument is invalid; one of the components is negative
1277 or too large.
1278 @end table
1279 @end deftypefun
1280
1281 @strong{Portability Note:}  The @code{select} function is a BSD Unix
1282 feature.
1283
1284 Here is an example showing how you can use @code{select} to establish a
1285 timeout period for reading from a file descriptor.  The @code{input_timeout}
1286 function blocks the calling process until input is available on the
1287 file descriptor, or until the timeout period expires.
1288
1289 @smallexample
1290 @include select.c.texi
1291 @end smallexample
1292
1293 There is another example showing the use of @code{select} to multiplex
1294 input from multiple sockets in @ref{Server Example}.
1295
1296
1297 @node Synchronizing I/O
1298 @section Synchronizing I/O operations
1299
1300 @cindex synchronizing
1301 In most modern operation systems the normal I/O operations are not
1302 executed synchronously.  I.e., even if a @code{write} system call
1303 returns this does not mean the data is actually written to the media,
1304 e.g., the disk.
1305
1306 In situations where synchronization points are necessary the user can
1307 use special functions which ensure that all operations finished before
1308 they return.
1309
1310 @comment unistd.h
1311 @comment X/Open
1312 @deftypefun int sync (void)
1313 A call to this function will not return as long as there is data which
1314 that is not written to the device.  All dirty buffers in the kernel will
1315 be written and so an overall consistent system can be achieved (if no
1316 other process in parallel writes data).
1317
1318 A prototype for @code{sync} can be found in @file{unistd.h}.
1319
1320 The return value is zero to indicate no error.
1321 @end deftypefun
1322
1323 More often it is wanted that not all data in the system is committed.
1324 Programs want to ensure that data written to a given file are all
1325 committed and in this situation @code{sync} is overkill.
1326
1327 @comment unistd.h
1328 @comment POSIX
1329 @deftypefun int fsync (int @var{fildes})
1330 The @code{fsync} can be used to make sure all data associated with the
1331 open file @var{fildes} is written to the device associated with the
1332 descriptor.  The function call does not return unless all actions have
1333 finished.
1334
1335 A prototype for @code{fsync} can be found in @file{unistd.h}.
1336
1337 This function is a cancelation point in multi-threaded programs.  This
1338 is a problem if the thread allocates some resources (like memory, file
1339 descriptors, semaphores or whatever) at the time @code{fsync} is
1340 called.  If the thread gets canceled these resources stay allocated
1341 until the program ends.  To avoid this calls to @code{fsync} should be
1342 protected using cancelation handlers.
1343 @c ref pthread_cleanup_push / pthread_cleanup_pop
1344
1345 The return value of the function is zero if no error occured.  Otherwise
1346 it is @math{-1} and the global variable @var{errno} is set to the
1347 following values:
1348 @table @code
1349 @item EBADF
1350 The descriptor @var{fildes} is not valid.
1351
1352 @item EINVAL
1353 No synchronization is possible since the system does not implement this.
1354 @end table
1355 @end deftypefun
1356
1357 Sometimes it is not even necessary to write all data associated with a
1358 file descriptor.  E.g., in database files which do not change in size it
1359 is enough to write all the file content data to the device.
1360 Meta-information like the modification time etc. are not that important
1361 and leaving such information uncommitted does not prevent a successful
1362 recovering of the file in case of a problem.
1363
1364 @comment unistd.h
1365 @comment POSIX
1366 @deftypefun int fdatasync (int @var{fildes})
1367 When a call to the @code{fdatasync} function returns it is made sure
1368 that all of the file data is written to the device.  For all pending I/O
1369 operations the parts guaranteeing data integrity finished.
1370
1371 Not all systems implement the @code{fdatasync} operation.  On systems
1372 missing this functionality @code{fdatasync} is emulated by a call to
1373 @code{fsync} since the performed actions are a superset of those
1374 required by @code{fdatasyn}.
1375
1376 The prototype for @code{fdatasync} is in @file{unistd.h}.
1377
1378 The return value of the function is zero if no error occured.  Otherwise
1379 it is @math{-1} and the global variable @var{errno} is set to the
1380 following values:
1381 @table @code
1382 @item EBADF
1383 The descriptor @var{fildes} is not valid.
1384
1385 @item EINVAL
1386 No synchronization is possible since the system does not implement this.
1387 @end table
1388 @end deftypefun
1389
1390
1391 @node Asynchronous I/O
1392 @section Perform I/O Operations in Parallel
1393
1394 The POSIX.1b standard defines a new set of I/O operations which can
1395 reduce the time an application spends waiting at I/O significantly.  The
1396 new functions allow a program to initiate one or more I/O operations and
1397 then immediately resume the normal work while the I/O operations are
1398 executed in parallel.  The functionality is available if the
1399 @file{unistd.h} file defines the symbol @code{_POSIX_ASYNCHRONOUS_IO}.
1400
1401 These functions are part of the library with realtime functions named
1402 @file{librt}.  They are not actually part of the @file{libc} binary.
1403 The implementation of these functions can be done using support in the
1404 kernel (if available) or using an implementation based on threads at
1405 userlevel.  In the latter case it might be necessary to link applications
1406 with the thread library @file{libpthread} in addition to @file{librt}.
1407
1408 All AIO operations operate on files which were opened previously.  There
1409 might be arbitrary many operations for one file running.  The
1410 asynchronous I/O operations are controlled using a data structure named
1411 @code{struct aiocb} (@dfn{AIO control block}).  It is defined in
1412 @file{aio.h} as follows.
1413
1414 @comment aio.h
1415 @comment POSIX.1b
1416 @deftp {Data Type} {struct aiocb}
1417 The POSIX.1b standard mandates that the @code{struct aiocb} structure
1418 contains at least the members described in the following table.  There
1419 might be more elements which are used by the implementation but
1420 depending on these elements is not portable and is highly deprecated.
1421
1422 @table @code
1423 @item int aio_fildes
1424 This element specifies the file descriptor which is used for the
1425 operation.  It must be a legal descriptor since otherwise the operation
1426 fails for obvious reasons.
1427
1428 The device on which the file is opened must allow the seek operation.
1429 I.e., it is not possible to use any of the AIO operations on devices
1430 like terminals where an @code{lseek} call would lead to an error.
1431
1432 @item off_t aio_offset
1433 This element specifies at which offset in the file the operation (input
1434 or output) is performed.  Since the operations are carried out in arbitrary
1435 order and more than one operation for one file descriptor can be
1436 started, one cannot expect a current read/write position of the file
1437 descriptor.
1438
1439 @item volatile void *aio_buf
1440 This is a pointer to the buffer with the data to be written or the place
1441 where the read data is stored.
1442
1443 @item size_t aio_nbytes
1444 This element specifies the length of the buffer pointed to by @code{aio_buf}.
1445
1446 @item int aio_reqprio
1447 If the platform has defined @code{_POSIX_PRIORITIZED_IO} and
1448 @code{_POSIX_PRIORITY_SCHEDULING} the AIO requests are
1449 processed based on the current scheduling priority.  The
1450 @code{aio_reqprio} element can then be used to lower the priority of the
1451 AIO operation.
1452
1453 @item struct sigevent aio_sigevent
1454 This element specifies how the calling process is notified once the
1455 operation terminates.  If the @code{sigev_notify} element is
1456 @code{SIGEV_NONE} no notification is send.  If it is @code{SIGEV_SIGNAL}
1457 the signal determined by @code{sigev_signo} is send.  Otherwise
1458 @code{sigev_notify} must be @code{SIGEV_THREAD}.  In this case a thread
1459 is created which starts executing the function pointed to by
1460 @code{sigev_notify_function}.
1461
1462 @item int aio_lio_opcode
1463 This element is only used by the @code{lio_listio} and
1464 @code{lio_listio64} functions.  Since these functions allow to start an
1465 arbitrary number of operations at once and since each operation can be
1466 input or output (or nothing) the information must be stored in the
1467 control block.  The possible values are:
1468
1469 @vtable @code
1470 @item LIO_READ
1471 Start a read operation.  Read from the file at position
1472 @code{aio_offset} and store the next @code{aio_nbytes} bytes in the
1473 buffer pointed to by @code{aio_buf}.
1474
1475 @item LIO_WRITE
1476 Start a write operation.  Write @code{aio_nbytes} bytes starting at
1477 @code{aio_buf} into the file starting at position @code{aio_offset}.
1478
1479 @item LIO_NOP
1480 Do nothing for this control block.  This value is useful sometimes when
1481 an array of @code{struct aiocb} values contains holes, i.e., some of the
1482 values must not be handled although the whole array is presented to the
1483 @code{lio_listio} function.
1484 @end vtable
1485 @end table
1486
1487 When the sources are compiled using @code{_FILE_OFFSET_BITS == 64} on a
1488 32 bits machine this type is in fact @code{struct aiocb64} since the LFS
1489 interface transparently replaces the @code{struct aiocb} definition.
1490 @end deftp
1491
1492 For use with the AIO functions defined in the LFS there is a similar type
1493 defined which replaces the types of the appropriate members with larger
1494 types but otherwise is equivalent to @code{struct aiocb}.  Especially
1495 all member names are the same.
1496
1497 @comment aio.h
1498 @comment POSIX.1b
1499 @deftp {Data Type} {struct aiocb64}
1500 @table @code
1501 @item int aio_fildes
1502 This element specifies the file descriptor which is used for the
1503 operation.  It must be a legal descriptor since otherwise the operation
1504 fails for obvious reasons.
1505
1506 The device on which the file is opened must allow the seek operation.
1507 I.e., it is not possible to use any of the AIO operations on devices
1508 like terminals where an @code{lseek} call would lead to an error.
1509
1510 @item off64_t aio_offset
1511 This element specified at which offset in the file the operation (input
1512 or output) is performed.  Since the operation are carried in arbitrary
1513 order and more than one operation for one file descriptor can be
1514 started, one cannot expect a current read/write position of the file
1515 descriptor.
1516
1517 @item volatile void *aio_buf
1518 This is a pointer to the buffer with the data to be written or the place
1519 where the ead data is stored.
1520
1521 @item size_t aio_nbytes
1522 This element specifies the length of the buffer pointed to by @code{aio_buf}.
1523
1524 @item int aio_reqprio
1525 If for the platform @code{_POSIX_PRIORITIZED_IO} and
1526 @code{_POSIX_PRIORITY_SCHEDULING} is defined the AIO requests are
1527 processed based on the current scheduling priority.  The
1528 @code{aio_reqprio} element can then be used to lower the priority of the
1529 AIO operation.
1530
1531 @item struct sigevent aio_sigevent
1532 This element specifies how the calling process is notified once the
1533 operation terminates.  If the @code{sigev_notify} element is
1534 @code{SIGEV_NONE} no notification is send.  If it is @code{SIGEV_SIGNAL}
1535 the signal determined by @code{sigev_signo} is send.  Otherwise
1536 @code{sigev_notify} must be @code{SIGEV_THREAD} in which case a thread
1537 which starts executing the function pointeed to by
1538 @code{sigev_notify_function}.
1539
1540 @item int aio_lio_opcode
1541 This element is only used by the @code{lio_listio} and
1542 @code{[lio_listio64} functions.  Since these functions allow to start an
1543 arbitrary number of operations at once and since each operation can be
1544 input or output (or nothing) the information must be stored in the
1545 control block.  See the description of @code{struct aiocb} for a description
1546 of the possible values.
1547 @end table
1548
1549 When the sources are compiled using @code{_FILE_OFFSET_BITS == 64} on a
1550 32 bits machine this type is available under the name @code{struct
1551 aiocb64} since the LFS replaces transparently the old interface.
1552 @end deftp
1553
1554 @menu
1555 * Asynchronous Reads/Writes::    Asynchronous Read and Write Operations.
1556 * Status of AIO Operations::     Getting the Status of AIO Operations.
1557 * Synchronizing AIO Operations:: Getting into a consistent state.
1558 * Cancel AIO Operations::        Cancelation of AIO Operations.
1559 * Configuration of AIO::         How to optimize the AIO implementation.
1560 @end menu
1561
1562 @node Asynchronous Reads/Writes
1563 @subsection Asynchronous Read and Write Operations
1564
1565 @comment aio.h
1566 @comment POSIX.1b
1567 @deftypefun int aio_read (struct aiocb *@var{aiocbp})
1568 This function initiates an asynchronous read operation.  The function
1569 call immediately returns after the operation was enqueued or when an
1570 error was encountered.
1571
1572 The first @code{aiocbp->aio_nbytes} bytes of the file for which
1573 @code{aiocbp->aio_fildes} is a descriptor are written to the buffer
1574 starting at @code{aiocbp->aio_buf}.  Reading starts at the absolute
1575 position @code{aiocbp->aio_offset} in the file.
1576
1577 If prioritized I/O is supported by the platform the
1578 @code{aiocbp->aio_reqprio} value is used to adjust the priority before
1579 the request is actually enqueued.
1580
1581 The calling process is notified about the termination of the read
1582 request according to the @code{aiocbp->aio_sigevent} value.
1583
1584 When @code{aio_read} returns the return value is zero if no error
1585 occurred that can be found before the process is enqueued.  If such an
1586 early error is found the function returns @math{-1} and sets
1587 @code{errno} to one of the following values.
1588
1589 @table @code
1590 @item EAGAIN
1591 The request was not enqueued due to (temporarily) exceeded resource
1592 limitations.
1593 @item ENOSYS
1594 The @code{aio_read} function is not implemented.
1595 @item EBADF
1596 The @code{aiocbp->aio_fildes} descriptor is not valid.  This condition
1597 needs not be recognized before enqueueing the request and so this error
1598 might also be signaled asynchronously.
1599 @item EINVAL
1600 The @code{aiocbp->aio_offset} or @code{aiocbp->aio_reqpiro} value is
1601 invalid.  This condition need not be recognized before enqueueing the
1602 request and so this error might also be signaled asynchrously.
1603 @end table
1604
1605 In the case @code{aio_read} returns zero the current status of the
1606 request can be queried using @code{aio_error} and @code{aio_return}
1607 functions.  As long as the value returned by @code{aio_error} is
1608 @code{EINPROGRESS} the operation has not yet completed.  If
1609 @code{aio_error} returns zero the operation successfully terminated,
1610 otherwise the value is to be interpreted as an error code.  If the
1611 function terminated the result of the operation can be get using a call
1612 to @code{aio_return}.  The returned value is the same as an equivalent
1613 call to @code{read} would have returned.  Possible error codes returned
1614 by @code{aio_error} are:
1615
1616 @table @code
1617 @item EBADF
1618 The @code{aiocbp->aio_fildes} descriptor is not valid.
1619 @item ECANCELED
1620 The operation was canceled before the operation was finished
1621 (@pxref{Cancel AIO Operations})
1622 @item EINVAL
1623 The @code{aiocbp->aio_offset} value is invalid.
1624 @end table
1625
1626 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1627 function is in fact @code{aio_read64} since the LFS interface transparently
1628 replaces the normal implementation.
1629 @end deftypefun
1630
1631 @comment aio.h
1632 @comment Unix98
1633 @deftypefun int aio_read64 (struct aiocb *@var{aiocbp})
1634 This function is similar to the @code{aio_read} function.  The only
1635 difference is that on @w{32 bits} machines the file descriptor should
1636 be opened in the large file mode.  Internally @code{aio_read64} uses
1637 functionality equivalent to @code{lseek64} (@pxref{File Position
1638 Primitive}) to position the file descriptor correctly for the reading,
1639 as opposed to @code{lseek} functionality used in @code{aio_read}.
1640
1641 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1642 function is available under the name @code{aio_read} and so transparently
1643 replaces the interface for small files on 32 bits machines.
1644 @end deftypefun
1645
1646 To write data asynchronously to a file there exists an equivalent pair
1647 of functions with a very similar interface.
1648
1649 @comment aio.h
1650 @comment POSIX.1b
1651 @deftypefun int aio_write (struct aiocb *@var{aiocbp})
1652 This function initiates an asynchronous write operation.  The function
1653 call immediately returns after the operation was enqueued or if before
1654 this happens an error was encountered.
1655
1656 The first @code{aiocbp->aio_nbytes} bytes from the buffer starting at
1657 @code{aiocbp->aio_buf} are written to the file for which
1658 @code{aiocbp->aio_fildes} is an descriptor, starting at the absolute
1659 position @code{aiocbp->aio_offset} in the file.
1660
1661 If prioritized I/O is supported by the platform the
1662 @code{aiocbp->aio_reqprio} value is used to adjust the priority before
1663 the request is actually enqueued.
1664
1665 The calling process is notified about the termination of the read
1666 request according to the @code{aiocbp->aio_sigevent} value.
1667
1668 When @code{aio_write} returns the return value is zero if no error
1669 occurred that can be found before the process is enqueued.  If such an
1670 early error is found the function returns @math{-1} and sets
1671 @code{errno} to one of the following values.
1672
1673 @table @code
1674 @item EAGAIN
1675 The request was not enqueued due to (temporarily) exceeded resource
1676 limitations.
1677 @item ENOSYS
1678 The @code{aio_write} function is not implemented.
1679 @item EBADF
1680 The @code{aiocbp->aio_fildes} descriptor is not valid.  This condition
1681 needs not be recognized before enqueueing the request and so this error
1682 might also be signaled asynchronously.
1683 @item EINVAL
1684 The @code{aiocbp->aio_offset} or @code{aiocbp->aio_reqpiro} value is
1685 invalid.  This condition needs not be recognized before enqueueing the
1686 request and so this error might also be signaled asynchronously.
1687 @end table
1688
1689 In the case @code{aio_write} returns zero the current status of the
1690 request can be queried using @code{aio_error} and @code{aio_return}
1691 functions.  As long as the value returned by @code{aio_error} is
1692 @code{EINPROGRESS} the operation has not yet completed.  If
1693 @code{aio_error} returns zero the operation successfully terminated,
1694 otherwise the value is to be interpreted as an error code.  If the
1695 function terminated the result of the operation can be get using a call
1696 to @code{aio_return}.  The returned value is the same as an equivalent
1697 call to @code{read} would have returned.  Possible error code returned
1698 by @code{aio_error} are:
1699
1700 @table @code
1701 @item EBADF
1702 The @code{aiocbp->aio_fildes} descriptor is not valid.
1703 @item ECANCELED
1704 The operation was canceled before the operation was finished
1705 (@pxref{Cancel AIO Operations})
1706 @item EINVAL
1707 The @code{aiocbp->aio_offset} value is invalid.
1708 @end table
1709
1710 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1711 function is in fact @code{aio_write64} since the LFS interface transparently
1712 replaces the normal implementation.
1713 @end deftypefun
1714
1715 @comment aio.h
1716 @comment Unix98
1717 @deftypefun int aio_write64 (struct aiocb *@var{aiocbp})
1718 This function is similar to the @code{aio_write} function.  The only
1719 difference is that on @w{32 bits} machines the file descriptor should
1720 be opened in the large file mode.  Internally @code{aio_write64} uses
1721 functionality equivalent to @code{lseek64} (@pxref{File Position
1722 Primitive}) to position the file descriptor correctly for the writing,
1723 as opposed to @code{lseek} functionality used in @code{aio_write}.
1724
1725 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1726 function is available under the name @code{aio_write} and so transparently
1727 replaces the interface for small files on 32 bits machines.
1728 @end deftypefun
1729
1730 Beside these functions with the more or less traditional interface
1731 POSIX.1b also defines a function with can initiate more than one
1732 operation at once and which can handled freely mixed read and write
1733 operation.  It is therefore similar to a combination of @code{readv} and
1734 @code{writev}.
1735
1736 @comment aio.h
1737 @comment POSIX.1b
1738 @deftypefun int lio_listio (int @var{mode}, struct aiocb *const @var{list}[], int @var{nent}, struct sigevent *@var{sig})
1739 The @code{lio_listio} function can be used to enqueue an arbitrary
1740 number of read and write requests at one time.  The requests can all be
1741 meant for the same file, all for different files or every solution in
1742 between.
1743
1744 @code{lio_listio} gets the @var{nent} requests from the array pointed to
1745 by @var{list}.  What operation has to be performed is determined by the
1746 @code{aio_lio_opcode} member in each element of @var{list}.  If this
1747 field is @code{LIO_READ} an read operation is queued, similar to a call
1748 of @code{aio_read} for this element of the array (except that the way
1749 the termination is signalled is different, as we will see below).  If
1750 the @code{aio_lio_opcode} member is @code{LIO_WRITE} an write operation
1751 is enqueued.  Otherwise the @code{aio_lio_opcode} must be @code{LIO_NOP}
1752 in which case this element of @var{list} is simply ignored.  This
1753 ``operation'' is useful in situations where one has a fixed array of
1754 @code{struct aiocb} elements from which only a few need to be handled at
1755 a time.  Another situation is where the @code{lio_listio} call was
1756 cancelled before all requests are processed (@pxref{Cancel AIO
1757 Operations}) and the remaining requests have to be reissued.
1758
1759 The other members of each element of the array pointed to by
1760 @code{list} must have values suitable for the operation as described in
1761 the documentation for @code{aio_read} and @code{aio_write} above.
1762
1763 The @var{mode} argument determines how @code{lio_listio} behaves after
1764 having enqueued all the requests.  If @var{mode} is @code{LIO_WAIT} it
1765 waits until all requests terminated.  Otherwise @var{mode} must be
1766 @code{LIO_NOWAIT} and in this case the function returns immediately after
1767 having enqueued all the requests.  In this case the caller gets a
1768 notification of the termination of all requests according to the
1769 @var{sig} parameter.  If @var{sig} is @code{NULL} no notification is
1770 send.  Otherwise a signal is sent or a thread is started, just as
1771 described in the description for @code{aio_read} or @code{aio_write}.
1772
1773 If @var{mode} is @code{LIO_WAIT} the return value of @code{lio_listio}
1774 is @math{0} when all requests completed successfully.  Otherwise the
1775 function return @math{-1} and @code{errno} is set accordingly.  To find
1776 out which request or requests failed one has to use the @code{aio_error}
1777 function on all the elements of the array @var{list}.
1778
1779 In case @var{mode} is @code{LIO_NOWAIT} the function return @math{0} if
1780 all requests were enqueued correctly.  The current state of the requests
1781 can be found using @code{aio_error} and @code{aio_return} as described
1782 above.  In case @code{lio_listio} returns @math{-1} in this mode the
1783 global variable @code{errno} is set accordingly.  If a request did not
1784 yet terminate a call to @code{aio_error} returns @code{EINPROGRESS}.  If
1785 the value is different the request is finished and the error value (or
1786 @math{0}) is returned and the result of the operation can be retrieved
1787 using @code{aio_return}.
1788
1789 Possible values for @code{errno} are:
1790
1791 @table @code
1792 @item EAGAIN
1793 The resources necessary to queue all the requests are not available in
1794 the moment.  The error status for each element of @var{list} must be
1795 checked which request failed.
1796
1797 Another reason could be that the system wide limit of AIO requests is
1798 exceeded.  This cannot be the case for the implementation on GNU systems
1799 since no arbitrary limits exist.
1800 @item EINVAL
1801 The @var{mode} parameter is invalid or @var{nent} is larger than
1802 @code{AIO_LISTIO_MAX}.
1803 @item EIO
1804 One or more of the request's I/O operations failed.  The error status of
1805 each request should be checked for which one failed.
1806 @item ENOSYS
1807 The @code{lio_listio} function is not supported.
1808 @end table
1809
1810 If the @var{mode} parameter is @code{LIO_NOWAIT} and the caller cancels
1811 an request the error status for this request returned by
1812 @code{aio_error} is @code{ECANCELED}.
1813
1814 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1815 function is in fact @code{lio_listio64} since the LFS interface
1816 transparently replaces the normal implementation.
1817 @end deftypefun
1818
1819 @comment aio.h
1820 @comment Unix98
1821 @deftypefun int lio_listio64 (int @var{mode}, struct aiocb *const @var{list}, int @var{nent}, struct sigevent *@var{sig})
1822 This function is similar to the @code{aio_listio} function.  The only
1823 difference is that only @w{32 bits} machines the file descriptor should
1824 be opened in the large file mode.  Internally @code{lio_listio64} uses
1825 functionality equivalent to @code{lseek64} (@pxref{File Position
1826 Primitive}) to position the file descriptor correctly for the reading or
1827 writing, as opposed to @code{lseek} functionality used in
1828 @code{lio_listio}.
1829
1830 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1831 function is available under the name @code{lio_listio} and so
1832 transparently replaces the interface for small files on 32 bits
1833 machines.
1834 @end deftypefun
1835
1836 @node Status of AIO Operations
1837 @subsection Getting the Status of AIO Operations
1838
1839 As already described in the documentation of the functions in the last
1840 section it must be possible to get information about the status of a I/O
1841 request.  When the operation is performed really asynchronous (as with
1842 @code{aio_read} and @code{aio_write} and with @code{aio_listio} when the
1843 mode is @code{LIO_NOWAIT}) one sometimes needs to know whether a
1844 specific request already terminated and if yes, what the result was..
1845 The following two function allow to get this kind of information.
1846
1847 @comment aio.h
1848 @comment POSIX.1b
1849 @deftypefun int aio_error (const struct aiocb *@var{aiocbp})
1850 This function determines the error state of the request described by the
1851 @code{struct aiocb} variable pointed to by @var{aiocbp}.  If the
1852 request has not yet terminated the value returned is always
1853 @code{EINPROGRESS}.  Once the request has terminated the value
1854 @code{aio_error} returns is either @math{0} if the request completed
1855 successfully or it returns the value which would be stored in the
1856 @code{errno} variable if the request would have been done using
1857 @code{read}, @code{write}, or @code{fsync}.
1858
1859 The function can return @code{ENOSYS} if it is not implemented.  It
1860 could also return @code{EINVAL} if the @var{aiocbp} parameter does not
1861 refer to an asynchronous operation whose return status is not yet known.
1862
1863 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1864 function is in fact @code{aio_error64} since the LFS interface
1865 transparently replaces the normal implementation.
1866 @end deftypefun
1867
1868 @comment aio.h
1869 @comment Unix98
1870 @deftypefun int aio_error64 (const struct aiocb64 *@var{aiocbp})
1871 This function is similar to @code{aio_error} with the only difference
1872 that the argument is a reference to a variable of type @code{struct
1873 aiocb64}.
1874
1875 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1876 function is available under the name @code{aio_error} and so
1877 transparently replaces the interface for small files on 32 bits
1878 machines.
1879 @end deftypefun
1880
1881 @comment aio.h
1882 @comment POSIX.1b
1883 @deftypefun ssize_t aio_return (const struct aiocb *@var{aiocbp})
1884 This function can be used to retrieve the return status of the operation
1885 carried out by the request described in the variable pointed to by
1886 @var{aiocbp}.  As long as the error status of this request as returned
1887 by @code{aio_error} is @code{EINPROGRESS} the return of this function is
1888 undefined.
1889
1890 Once the request is finished this function can be used exactly once to
1891 retrieve the return value.  Following calls might lead to undefined
1892 behaviour.  The return value itself is the value which would have been
1893 returned by the @code{read}, @code{write}, or @code{fsync} call.
1894
1895 The function can return @code{ENOSYS} if it is not implemented.  It
1896 could also return @code{EINVAL} if the @var{aiocbp} parameter does not
1897 refer to an asynchronous operation whose return status is not yet known.
1898
1899 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1900 function is in fact @code{aio_return64} since the LFS interface
1901 transparently replaces the normal implementation.
1902 @end deftypefun
1903
1904 @comment aio.h
1905 @comment Unix98
1906 @deftypefun int aio_return64 (const struct aiocb64 *@var{aiocbp})
1907 This function is similar to @code{aio_return} with the only difference
1908 that the argument is a reference to a variable of type @code{struct
1909 aiocb64}.
1910
1911 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1912 function is available under the name @code{aio_return} and so
1913 transparently replaces the interface for small files on 32 bits
1914 machines.
1915 @end deftypefun
1916
1917 @node Synchronizing AIO Operations
1918 @subsection Getting into a Consistent State
1919
1920 When dealing with asynchronous operations it is sometimes necessary to
1921 get into a consistent state.  This would mean for AIO that one wants to
1922 know whether a certain request or a group of request were processed.
1923 This could be done by waiting for the notification sent by the system
1924 after the operation terminated but this sometimes would mean wasting
1925 resources (mainly computation time).  Instead POSIX.1b defines two
1926 functions which will help with most kinds of consistency.
1927
1928 The @code{aio_fsync} and @code{aio_fsync64} functions are only available
1929 if in @file{unistd.h} the symbol @code{_POSIX_SYNCHRONIZED_IO} is
1930 defined.
1931
1932 @cindex synchronizing
1933 @comment aio.h
1934 @comment POSIX.1b
1935 @deftypefun int aio_fsync (int @var{op}, struct aiocb *@var{aiocbp})
1936 Calling this function forces all I/O operations operating queued at the
1937 time of the function call operating on the file descriptor
1938 @code{aiocbp->aio_fildes} into the synchronized I/O completion state
1939 (@pxref{Synchronizing I/O}).  The @code{aio_fsync} function return
1940 immediately but the notification through the method described in
1941 @code{aiocbp->aio_sigevent} will happen only after all requests for this
1942 file descriptor terminated and the file is synchronized.  This also
1943 means that requests for this very same file descriptor which are queued
1944 after the synchronization request are not effected.
1945
1946 If @var{op} is @code{O_DSYNC} the synchronization happens as with a call
1947 to @code{fdatasync}.  Otherwise @var{op} should be @code{O_SYNC} and
1948 the synchronization happens as with @code{fsync}.
1949
1950 As long as the synchronization has not happened a call to
1951 @code{aio_error} with the reference to the object pointed to by
1952 @var{aiocbp} returns @code{EINPROGRESS}.  Once the synchronization is
1953 done @code{aio_error} return @math{0} if the synchronization was not
1954 successful.  Otherwise the value returned is the value to which the
1955 @code{fsync} or @code{fdatasync} function would have set the
1956 @code{errno} variable.  In this case nothing can be assumed about the
1957 consistency for the data written to this file descriptor.
1958
1959 The return value of this function is @math{0} if the request was
1960 successfully filed.  Otherwise the return value is @math{-1} and
1961 @code{errno} is set to one of the following values:
1962
1963 @table @code
1964 @item EAGAIN
1965 The request could not be enqueued due to temporary lack of resources.
1966 @item EBADF
1967 The file descriptor @code{aiocbp->aio_fildes} is not valid or not open
1968 for writing.
1969 @item EINVAL
1970 The implementation does not support I/O synchronization or the @var{op}
1971 parameter is other than @code{O_DSYNC} and @code{O_SYNC}.
1972 @item ENOSYS
1973 This function is not implemented.
1974 @end table
1975
1976 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1977 function is in fact @code{aio_return64} since the LFS interface
1978 transparently replaces the normal implementation.
1979 @end deftypefun
1980
1981 @comment aio.h
1982 @comment Unix98
1983 @deftypefun int aio_fsync64 (int @var{op}, struct aiocb64 *@var{aiocbp})
1984 This function is similar to @code{aio_fsync} with the only difference
1985 that the argument is a reference to a variable of type @code{struct
1986 aiocb64}.
1987
1988 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
1989 function is available under the name @code{aio_fsync} and so
1990 transparently replaces the interface for small files on 32 bits
1991 machines.
1992 @end deftypefun
1993
1994 Another method of synchronization is to wait until one or more requests of a
1995 specific set terminated.  This could be achieved by the @code{aio_*}
1996 functions to notify the initiating process about the termination but in
1997 some situations this is not the ideal solution.  In a program which
1998 constantly updates clients somehow connected to the server it is not
1999 always the best solution to go round robin since some connections might
2000 be slow.  On the other hand letting the @code{aio_*} function notify the
2001 caller might also be not the best solution since whenever the process
2002 works on preparing data for on client it makes no sense to be
2003 interrupted by a notification since the new client will not be handled
2004 before the current client is served.  For situations like this
2005 @code{aio_suspend} should be used.
2006
2007 @comment aio.h
2008 @comment POSIX.1b
2009 @deftypefun int aio_suspend (const struct aiocb *const @var{list}[], int @var{nent}, const struct timespec *@var{timeout})
2010 When calling this function the calling thread is suspended until at
2011 least one of the requests pointed to by the @var{nent} elements of the
2012 array @var{list} has completed.  If any of the requests already has
2013 completed at the time @code{aio_suspend} is called the function returns
2014 immediately.  Whether a request has terminated or not is done by
2015 comparing the error status of the request with @code{EINPROGRESS}.  If
2016 an element of @var{list} is @code{NULL} the entry is simply ignored.
2017
2018 If no request has finished the calling process is suspended.  If
2019 @var{timeout} is @code{NULL} the process is not waked until a request
2020 finished.  If @var{timeout} is not @code{NULL} the process remains
2021 suspended at as long as specified in @var{timeout}.  In this case
2022 @code{aio_suspend} returns with an error.
2023
2024 The return value of the function is @math{0} if one or more requests
2025 from the @var{list} have terminated.  Otherwise the function returns
2026 @math{-1} and @code{errno} is set to one of the following values:
2027
2028 @table @code
2029 @item EAGAIN
2030 None of the requests from the @var{list} completed in the time specified
2031 by @var{timeout}.
2032 @item EINTR
2033 A signal interrupted the @code{aio_suspend} function.  This signal might
2034 also be sent by the AIO implementation while signalling the termination
2035 of one of the requests.
2036 @item ENOSYS
2037 The @code{aio_suspend} function is not implemented.
2038 @end table
2039
2040 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2041 function is in fact @code{aio_suspend64} since the LFS interface
2042 transparently replaces the normal implementation.
2043 @end deftypefun
2044
2045 @comment aio.h
2046 @comment Unix98
2047 @deftypefun int aio_suspend64 (const struct aiocb64 *const @var{list}[], int @var{nent}, const struct timespec *@var{timeout})
2048 This function is similar to @code{aio_suspend} with the only difference
2049 that the argument is a reference to a variable of type @code{struct
2050 aiocb64}.
2051
2052 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2053 function is available under the name @code{aio_suspend} and so
2054 transparently replaces the interface for small files on 32 bits
2055 machines.
2056 @end deftypefun
2057
2058 @node Cancel AIO Operations
2059 @subsection Cancelation of AIO Operations
2060
2061 When one or more requests are asynchronously processed it might be
2062 useful in some situations to cancel a selected operation, e.g., if it
2063 becomes obvious that the written data is not anymore accurate and would
2064 have to be overwritten soon.  As an example assume an application, which
2065 writes data in files in a situation where new incoming data would have
2066 to be written in a file which will be updated by an enqueued request.
2067 The POSIX AIO implementation provides such a function but this function
2068 is not capable to force the cancelation of the request.  It is up to the
2069 implementation to decide whether it is possible to cancel the operation
2070 or not.  Therefore using this function is merely a hint.
2071
2072 @comment aio.h
2073 @comment POSIX.1b
2074 @deftypefun int aio_cancel (int @var{fildes}, struct aiocb *@var{aiocbp})
2075 The @code{aio_cancel} function can be used to cancel one or more
2076 outstanding requests.  If the @var{aiocbp} parameter is @code{NULL} the
2077 function tries to cancel all outstanding requests which would process
2078 the file descriptor @var{fildes} (i.e.,, whose @code{aio_fildes} member
2079 is @var{fildes}).  If @var{aiocbp} is not @code{NULL} the very specific
2080 request pointed to by @var{aiocbp} is tried to be canceled.
2081
2082 For requests which were successfully canceled the normal notification
2083 about the termination of the request should take place.  I.e., depending
2084 on the @code{struct sigevent} object which controls this, nothing
2085 happens, a signal is sent or a thread is started.  If the request cannot
2086 be canceled it terminates the usual way after performing te operation.
2087
2088 After a request is successfully canceled a call to @code{aio_error} with
2089 a reference to this request as the parameter will return
2090 @code{ECANCELED} and a call to @code{aio_return} will return @math{-1}.
2091 If the request wasn't canceled and is still running the error status is
2092 still @code{EINPROGRESS}.
2093
2094 The return value of the function is @code{AIO_CANCELED} if there were
2095 requests which haven't terminated and which successfully were canceled.
2096 If there is one or more request left which couldn't be canceled the
2097 return value is @code{AIO_NOTCANCELED}.  In this case @code{aio_error}
2098 must be used to find out which of the perhaps multiple requests (in
2099 @var{aiocbp} is @code{NULL}) wasn't successfully canceled.  If all
2100 requests already terminated at the time @code{aio_cancel} is called the
2101 return value is @code{AIO_ALLDONE}.
2102
2103 If an error occurred during the execution of @code{aio_cancel} the
2104 function returns @math{-1} and sets @code{errno} to one of the following
2105 values.
2106
2107 @table @code
2108 @item EBADF
2109 The file descriptor @var{fildes} is not valid.
2110 @item ENOSYS
2111 @code{aio_cancel} is not implemented.
2112 @end table
2113
2114 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2115 function is in fact @code{aio_cancel64} since the LFS interface
2116 transparently replaces the normal implementation.
2117 @end deftypefun
2118
2119 @comment aio.h
2120 @comment Unix98
2121 @deftypefun int aio_cancel64 (int @var{fildes}, struct aiocb *@var{aiocbp})
2122 This function is similar to @code{aio_cancel} with the only difference
2123 that the argument is a reference to a variable of type @code{struct
2124 aiocb64}.
2125
2126 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} this
2127 function is available under the name @code{aio_cancel} and so
2128 transparently replaces the interface for small files on 32 bits
2129 machines.
2130 @end deftypefun
2131
2132 @node Configuration of AIO
2133 @subsection How to optimize the AIO implementation
2134
2135 The POSIX standard does not specify how the AIO functions are
2136 implemented.  They could be system calls but it is also possible to
2137 emulate them at userlevel.
2138
2139 At least the available implementation at the point of this writing is a
2140 userlevel implementation which uses threads for handling the enqueued
2141 requests.  This implementation requires to make some decisions about
2142 limitations but hard limitations are something which better should be
2143 avoided the GNU C library implementation provides a mean to tune the AIO
2144 implementation individually for each use.
2145
2146 @comment aio.h
2147 @comment GNU
2148 @deftp {Data Type} {struct aioinit}
2149 This data type is used to pass the configuration or tunable parameters
2150 to the implementation.  The program has to initialize the members of
2151 this struct and pass it to the implementation using the @code{aio_init}
2152 function.
2153
2154 @table @code
2155 @item int aio_threads
2156 This member specifies the maximal number of threads which must be used
2157 at any one time.
2158 @item int aio_num
2159 This number provides an estimate on the maximal number of simultaneously
2160 enqueued requests.
2161 @item int aio_locks
2162 @c What?
2163 @item int aio_usedba
2164 @c What?
2165 @item int aio_debug
2166 @c What?
2167 @item int aio_numusers
2168 @c What?
2169 @item int aio_reserved[2]
2170 @c What?
2171 @end table
2172 @end deftp
2173
2174 @comment aio.h
2175 @comment GNU
2176 @deftypefun void aio_init (const struct aioinit *@var{init})
2177 This function must be called before any other AIO function.  Calling it
2178 is completely voluntarily since it only is meant to help the AIO
2179 implementation to perform better.
2180
2181 Before calling the @code{aio_init} function the members of a variable of
2182 type @code{struct aioinit} must be initialized.  Then a reference to
2183 this variable is passed as the parameter to @code{aio_init} which itself
2184 may or may not pay attention to the hints.
2185
2186 The function has no return value and no error cases are defined.  It is
2187 a extension which follows a proposal from the SGI implementation in
2188 @w{Irix 6}.  It is not covered by POSIX.1b or Unix98.
2189 @end deftypefun
2190
2191 @node Control Operations
2192 @section Control Operations on Files
2193
2194 @cindex control operations on files
2195 @cindex @code{fcntl} function
2196 This section describes how you can perform various other operations on
2197 file descriptors, such as inquiring about or setting flags describing
2198 the status of the file descriptor, manipulating record locks, and the
2199 like.  All of these operations are performed by the function @code{fcntl}.
2200
2201 The second argument to the @code{fcntl} function is a command that
2202 specifies which operation to perform.  The function and macros that name
2203 various flags that are used with it are declared in the header file
2204 @file{fcntl.h}.  Many of these flags are also used by the @code{open}
2205 function; see @ref{Opening and Closing Files}.
2206 @pindex fcntl.h
2207
2208 @comment fcntl.h
2209 @comment POSIX.1
2210 @deftypefun int fcntl (int @var{filedes}, int @var{command}, @dots{})
2211 The @code{fcntl} function performs the operation specified by
2212 @var{command} on the file descriptor @var{filedes}.  Some commands
2213 require additional arguments to be supplied.  These additional arguments
2214 and the return value and error conditions are given in the detailed
2215 descriptions of the individual commands.
2216
2217 Briefly, here is a list of what the various commands are.
2218
2219 @table @code
2220 @item F_DUPFD
2221 Duplicate the file descriptor (return another file descriptor pointing
2222 to the same open file).  @xref{Duplicating Descriptors}.
2223
2224 @item F_GETFD
2225 Get flags associated with the file descriptor.  @xref{Descriptor Flags}.
2226
2227 @item F_SETFD
2228 Set flags associated with the file descriptor.  @xref{Descriptor Flags}.
2229
2230 @item F_GETFL
2231 Get flags associated with the open file.  @xref{File Status Flags}.
2232
2233 @item F_SETFL
2234 Set flags associated with the open file.  @xref{File Status Flags}.
2235
2236 @item F_GETLK
2237 Get a file lock.  @xref{File Locks}.
2238
2239 @item F_SETLK
2240 Set or clear a file lock.  @xref{File Locks}.
2241
2242 @item F_SETLKW
2243 Like @code{F_SETLK}, but wait for completion.  @xref{File Locks}.
2244
2245 @item F_GETOWN
2246 Get process or process group ID to receive @code{SIGIO} signals.
2247 @xref{Interrupt Input}.
2248
2249 @item F_SETOWN
2250 Set process or process group ID to receive @code{SIGIO} signals.
2251 @xref{Interrupt Input}.
2252 @end table
2253
2254 This function is a cancelation point in multi-threaded programs.  This
2255 is a problem if the thread allocates some resources (like memory, file
2256 descriptors, semaphores or whatever) at the time @code{fcntl} is
2257 called.  If the thread gets canceled these resources stay allocated
2258 until the program ends.  To avoid this calls to @code{fcntl} should be
2259 protected using cancelation handlers.
2260 @c ref pthread_cleanup_push / pthread_cleanup_pop
2261 @end deftypefun
2262
2263
2264 @node Duplicating Descriptors
2265 @section Duplicating Descriptors
2266
2267 @cindex duplicating file descriptors
2268 @cindex redirecting input and output
2269
2270 You can @dfn{duplicate} a file descriptor, or allocate another file
2271 descriptor that refers to the same open file as the original.  Duplicate
2272 descriptors share one file position and one set of file status flags
2273 (@pxref{File Status Flags}), but each has its own set of file descriptor
2274 flags (@pxref{Descriptor Flags}).
2275
2276 The major use of duplicating a file descriptor is to implement
2277 @dfn{redirection} of input or output:  that is, to change the
2278 file or pipe that a particular file descriptor corresponds to.
2279
2280 You can perform this operation using the @code{fcntl} function with the
2281 @code{F_DUPFD} command, but there are also convenient functions
2282 @code{dup} and @code{dup2} for duplicating descriptors.
2283
2284 @pindex unistd.h
2285 @pindex fcntl.h
2286 The @code{fcntl} function and flags are declared in @file{fcntl.h},
2287 while prototypes for @code{dup} and @code{dup2} are in the header file
2288 @file{unistd.h}.
2289
2290 @comment unistd.h
2291 @comment POSIX.1
2292 @deftypefun int dup (int @var{old})
2293 This function copies descriptor @var{old} to the first available
2294 descriptor number (the first number not currently open).  It is
2295 equivalent to @code{fcntl (@var{old}, F_DUPFD, 0)}.
2296 @end deftypefun
2297
2298 @comment unistd.h
2299 @comment POSIX.1
2300 @deftypefun int dup2 (int @var{old}, int @var{new})
2301 This function copies the descriptor @var{old} to descriptor number
2302 @var{new}.
2303
2304 If @var{old} is an invalid descriptor, then @code{dup2} does nothing; it
2305 does not close @var{new}.  Otherwise, the new duplicate of @var{old}
2306 replaces any previous meaning of descriptor @var{new}, as if @var{new}
2307 were closed first.
2308
2309 If @var{old} and @var{new} are different numbers, and @var{old} is a
2310 valid descriptor number, then @code{dup2} is equivalent to:
2311
2312 @smallexample
2313 close (@var{new});
2314 fcntl (@var{old}, F_DUPFD, @var{new})
2315 @end smallexample
2316
2317 However, @code{dup2} does this atomically; there is no instant in the
2318 middle of calling @code{dup2} at which @var{new} is closed and not yet a
2319 duplicate of @var{old}.
2320 @end deftypefun
2321
2322 @comment fcntl.h
2323 @comment POSIX.1
2324 @deftypevr Macro int F_DUPFD
2325 This macro is used as the @var{command} argument to @code{fcntl}, to
2326 copy the file descriptor given as the first argument.
2327
2328 The form of the call in this case is:
2329
2330 @smallexample
2331 fcntl (@var{old}, F_DUPFD, @var{next-filedes})
2332 @end smallexample
2333
2334 The @var{next-filedes} argument is of type @code{int} and specifies that
2335 the file descriptor returned should be the next available one greater
2336 than or equal to this value.
2337
2338 The return value from @code{fcntl} with this command is normally the value
2339 of the new file descriptor.  A return value of @code{-1} indicates an
2340 error.  The following @code{errno} error conditions are defined for
2341 this command:
2342
2343 @table @code
2344 @item EBADF
2345 The @var{old} argument is invalid.
2346
2347 @item EINVAL
2348 The @var{next-filedes} argument is invalid.
2349
2350 @item EMFILE
2351 There are no more file descriptors available---your program is already
2352 using the maximum.  In BSD and GNU, the maximum is controlled by a
2353 resource limit that can be changed; @pxref{Limits on Resources}, for
2354 more information about the @code{RLIMIT_NOFILE} limit.
2355 @end table
2356
2357 @code{ENFILE} is not a possible error code for @code{dup2} because
2358 @code{dup2} does not create a new opening of a file; duplicate
2359 descriptors do not count toward the limit which @code{ENFILE}
2360 indicates.  @code{EMFILE} is possible because it refers to the limit on
2361 distinct descriptor numbers in use in one process.
2362 @end deftypevr
2363
2364 Here is an example showing how to use @code{dup2} to do redirection.
2365 Typically, redirection of the standard streams (like @code{stdin}) is
2366 done by a shell or shell-like program before calling one of the
2367 @code{exec} functions (@pxref{Executing a File}) to execute a new
2368 program in a child process.  When the new program is executed, it
2369 creates and initializes the standard streams to point to the
2370 corresponding file descriptors, before its @code{main} function is
2371 invoked.
2372
2373 So, to redirect standard input to a file, the shell could do something
2374 like:
2375
2376 @smallexample
2377 pid = fork ();
2378 if (pid == 0)
2379   @{
2380     char *filename;
2381     char *program;
2382     int file;
2383     @dots{}
2384     file = TEMP_FAILURE_RETRY (open (filename, O_RDONLY));
2385     dup2 (file, STDIN_FILENO);
2386     TEMP_FAILURE_RETRY (close (file));
2387     execv (program, NULL);
2388   @}
2389 @end smallexample
2390
2391 There is also a more detailed example showing how to implement redirection
2392 in the context of a pipeline of processes in @ref{Launching Jobs}.
2393
2394
2395 @node Descriptor Flags
2396 @section File Descriptor Flags
2397 @cindex file descriptor flags
2398
2399 @dfn{File descriptor flags} are miscellaneous attributes of a file
2400 descriptor.  These flags are associated with particular file
2401 descriptors, so that if you have created duplicate file descriptors
2402 from a single opening of a file, each descriptor has its own set of flags.
2403
2404 Currently there is just one file descriptor flag: @code{FD_CLOEXEC},
2405 which causes the descriptor to be closed if you use any of the
2406 @code{exec@dots{}} functions (@pxref{Executing a File}).
2407
2408 The symbols in this section are defined in the header file
2409 @file{fcntl.h}.
2410 @pindex fcntl.h
2411
2412 @comment fcntl.h
2413 @comment POSIX.1
2414 @deftypevr Macro int F_GETFD
2415 This macro is used as the @var{command} argument to @code{fcntl}, to
2416 specify that it should return the file descriptor flags associated
2417 with the @var{filedes} argument.
2418
2419 The normal return value from @code{fcntl} with this command is a
2420 nonnegative number which can be interpreted as the bitwise OR of the
2421 individual flags (except that currently there is only one flag to use).
2422
2423 In case of an error, @code{fcntl} returns @code{-1}.  The following
2424 @code{errno} error conditions are defined for this command:
2425
2426 @table @code
2427 @item EBADF
2428 The @var{filedes} argument is invalid.
2429 @end table
2430 @end deftypevr
2431
2432
2433 @comment fcntl.h
2434 @comment POSIX.1
2435 @deftypevr Macro int F_SETFD
2436 This macro is used as the @var{command} argument to @code{fcntl}, to
2437 specify that it should set the file descriptor flags associated with the
2438 @var{filedes} argument.  This requires a third @code{int} argument to
2439 specify the new flags, so the form of the call is:
2440
2441 @smallexample
2442 fcntl (@var{filedes}, F_SETFD, @var{new-flags})
2443 @end smallexample
2444
2445 The normal return value from @code{fcntl} with this command is an
2446 unspecified value other than @code{-1}, which indicates an error.
2447 The flags and error conditions are the same as for the @code{F_GETFD}
2448 command.
2449 @end deftypevr
2450
2451 The following macro is defined for use as a file descriptor flag with
2452 the @code{fcntl} function.  The value is an integer constant usable
2453 as a bit mask value.
2454
2455 @comment fcntl.h
2456 @comment POSIX.1
2457 @deftypevr Macro int FD_CLOEXEC
2458 @cindex close-on-exec (file descriptor flag)
2459 This flag specifies that the file descriptor should be closed when
2460 an @code{exec} function is invoked; see @ref{Executing a File}.  When
2461 a file descriptor is allocated (as with @code{open} or @code{dup}),
2462 this bit is initially cleared on the new file descriptor, meaning that
2463 descriptor will survive into the new program after @code{exec}.
2464 @end deftypevr
2465
2466 If you want to modify the file descriptor flags, you should get the
2467 current flags with @code{F_GETFD} and modify the value.  Don't assume
2468 that the flags listed here are the only ones that are implemented; your
2469 program may be run years from now and more flags may exist then.  For
2470 example, here is a function to set or clear the flag @code{FD_CLOEXEC}
2471 without altering any other flags:
2472
2473 @smallexample
2474 /* @r{Set the @code{FD_CLOEXEC} flag of @var{desc} if @var{value} is nonzero,}
2475    @r{or clear the flag if @var{value} is 0.}
2476    @r{Return 0 on success, or -1 on error with @code{errno} set.} */
2477
2478 int
2479 set_cloexec_flag (int desc, int value)
2480 @{
2481   int oldflags = fcntl (desc, F_GETFD, 0);
2482   /* @r{If reading the flags failed, return error indication now.}
2483   if (oldflags < 0)
2484     return oldflags;
2485   /* @r{Set just the flag we want to set.} */
2486   if (value != 0)
2487     oldflags |= FD_CLOEXEC;
2488   else
2489     oldflags &= ~FD_CLOEXEC;
2490   /* @r{Store modified flag word in the descriptor.} */
2491   return fcntl (desc, F_SETFD, oldflags);
2492 @}
2493 @end smallexample
2494
2495 @node File Status Flags
2496 @section File Status Flags
2497 @cindex file status flags
2498
2499 @dfn{File status flags} are used to specify attributes of the opening of a
2500 file.  Unlike the file descriptor flags discussed in @ref{Descriptor
2501 Flags}, the file status flags are shared by duplicated file descriptors
2502 resulting from a single opening of the file.  The file status flags are
2503 specified with the @var{flags} argument to @code{open};
2504 @pxref{Opening and Closing Files}.
2505
2506 File status flags fall into three categories, which are described in the
2507 following sections.
2508
2509 @itemize @bullet
2510 @item
2511 @ref{Access Modes}, specify what type of access is allowed to the
2512 file: reading, writing, or both.  They are set by @code{open} and are
2513 returned by @code{fcntl}, but cannot be changed.
2514
2515 @item
2516 @ref{Open-time Flags}, control details of what @code{open} will do.
2517 These flags are not preserved after the @code{open} call.
2518
2519 @item
2520 @ref{Operating Modes}, affect how operations such as @code{read} and
2521 @code{write} are done.  They are set by @code{open}, and can be fetched or
2522 changed with @code{fcntl}.
2523 @end itemize
2524
2525 The symbols in this section are defined in the header file
2526 @file{fcntl.h}.
2527 @pindex fcntl.h
2528
2529 @menu
2530 * Access Modes::                Whether the descriptor can read or write.
2531 * Open-time Flags::             Details of @code{open}.
2532 * Operating Modes::             Special modes to control I/O operations.
2533 * Getting File Status Flags::   Fetching and changing these flags.
2534 @end menu
2535
2536 @node Access Modes
2537 @subsection File Access Modes
2538
2539 The file access modes allow a file descriptor to be used for reading,
2540 writing, or both.  (In the GNU system, they can also allow none of these,
2541 and allow execution of the file as a program.)  The access modes are chosen
2542 when the file is opened, and never change.
2543
2544 @comment fcntl.h
2545 @comment POSIX.1
2546 @deftypevr Macro int O_RDONLY
2547 Open the file for read access.
2548 @end deftypevr
2549
2550 @comment fcntl.h
2551 @comment POSIX.1
2552 @deftypevr Macro int O_WRONLY
2553 Open the file for write access.
2554 @end deftypevr
2555
2556 @comment fcntl.h
2557 @comment POSIX.1
2558 @deftypevr Macro int O_RDWR
2559 Open the file for both reading and writing.
2560 @end deftypevr
2561
2562 In the GNU system (and not in other systems), @code{O_RDONLY} and
2563 @code{O_WRONLY} are independent bits that can be bitwise-ORed together,
2564 and it is valid for either bit to be set or clear.  This means that
2565 @code{O_RDWR} is the same as @code{O_RDONLY|O_WRONLY}.  A file access
2566 mode of zero is permissible; it allows no operations that do input or
2567 output to the file, but does allow other operations such as
2568 @code{fchmod}.  On the GNU system, since ``read-only'' or ``write-only''
2569 is a misnomer, @file{fcntl.h} defines additional names for the file
2570 access modes.  These names are preferred when writing GNU-specific code.
2571 But most programs will want to be portable to other POSIX.1 systems and
2572 should use the POSIX.1 names above instead.
2573
2574 @comment fcntl.h
2575 @comment GNU
2576 @deftypevr Macro int O_READ
2577 Open the file for reading.  Same as @code{O_RDWR}; only defined on GNU.
2578 @end deftypevr
2579
2580 @comment fcntl.h
2581 @comment GNU
2582 @deftypevr Macro int O_WRITE
2583 Open the file for reading.  Same as @code{O_WRONLY}; only defined on GNU.
2584 @end deftypevr
2585
2586 @comment fcntl.h
2587 @comment GNU
2588 @deftypevr Macro int O_EXEC
2589 Open the file for executing.  Only defined on GNU.
2590 @end deftypevr
2591
2592 To determine the file access mode with @code{fcntl}, you must extract
2593 the access mode bits from the retrieved file status flags.  In the GNU
2594 system, you can just test the @code{O_READ} and @code{O_WRITE} bits in
2595 the flags word.  But in other POSIX.1 systems, reading and writing
2596 access modes are not stored as distinct bit flags.  The portable way to
2597 extract the file access mode bits is with @code{O_ACCMODE}.
2598
2599 @comment fcntl.h
2600 @comment POSIX.1
2601 @deftypevr Macro int O_ACCMODE
2602 This macro stands for a mask that can be bitwise-ANDed with the file
2603 status flag value to produce a value representing the file access mode.
2604 The mode will be @code{O_RDONLY}, @code{O_WRONLY}, or @code{O_RDWR}.
2605 (In the GNU system it could also be zero, and it never includes the
2606 @code{O_EXEC} bit.)
2607 @end deftypevr
2608
2609 @node Open-time Flags
2610 @subsection Open-time Flags
2611
2612 The open-time flags specify options affecting how @code{open} will behave.
2613 These options are not preserved once the file is open.  The exception to
2614 this is @code{O_NONBLOCK}, which is also an I/O operating mode and so it
2615 @emph{is} saved.  @xref{Opening and Closing Files}, for how to call
2616 @code{open}.
2617
2618 There are two sorts of options specified by open-time flags.
2619
2620 @itemize @bullet
2621 @item
2622 @dfn{File name translation flags} affect how @code{open} looks up the
2623 file name to locate the file, and whether the file can be created.
2624 @cindex file name translation flags
2625 @cindex flags, file name translation
2626
2627 @item
2628 @dfn{Open-time action flags} specify extra operations that @code{open} will
2629 perform on the file once it is open.
2630 @cindex open-time action flags
2631 @cindex flags, open-time action
2632 @end itemize
2633
2634 Here are the file name translation flags.
2635
2636 @comment fcntl.h
2637 @comment POSIX.1
2638 @deftypevr Macro int O_CREAT
2639 If set, the file will be created if it doesn't already exist.
2640 @c !!! mode arg, umask
2641 @cindex create on open (file status flag)
2642 @end deftypevr
2643
2644 @comment fcntl.h
2645 @comment POSIX.1
2646 @deftypevr Macro int O_EXCL
2647 If both @code{O_CREAT} and @code{O_EXCL} are set, then @code{open} fails
2648 if the specified file already exists.  This is guaranteed to never
2649 clobber an existing file.
2650 @end deftypevr
2651
2652 @comment fcntl.h
2653 @comment POSIX.1
2654 @deftypevr Macro int O_NONBLOCK
2655 @cindex non-blocking open
2656 This prevents @code{open} from blocking for a ``long time'' to open the
2657 file.  This is only meaningful for some kinds of files, usually devices
2658 such as serial ports; when it is not meaningful, it is harmless and
2659 ignored.  Often opening a port to a modem blocks until the modem reports
2660 carrier detection; if @code{O_NONBLOCK} is specified, @code{open} will
2661 return immediately without a carrier.
2662
2663 Note that the @code{O_NONBLOCK} flag is overloaded as both an I/O operating
2664 mode and a file name translation flag.  This means that specifying
2665 @code{O_NONBLOCK} in @code{open} also sets nonblocking I/O mode;
2666 @pxref{Operating Modes}.  To open the file without blocking but do normal
2667 I/O that blocks, you must call @code{open} with @code{O_NONBLOCK} set and
2668 then call @code{fcntl} to turn the bit off.
2669 @end deftypevr
2670
2671 @comment fcntl.h
2672 @comment POSIX.1
2673 @deftypevr Macro int O_NOCTTY
2674 If the named file is a terminal device, don't make it the controlling
2675 terminal for the process.  @xref{Job Control}, for information about
2676 what it means to be the controlling terminal.
2677
2678 In the GNU system and 4.4 BSD, opening a file never makes it the
2679 controlling terminal and @code{O_NOCTTY} is zero.  However, other
2680 systems may use a nonzero value for @code{O_NOCTTY} and set the
2681 controlling terminal when you open a file that is a terminal device; so
2682 to be portable, use @code{O_NOCTTY} when it is important to avoid this.
2683 @cindex controlling terminal, setting
2684 @end deftypevr
2685
2686 The following three file name translation flags exist only in the GNU system.
2687
2688 @comment fcntl.h
2689 @comment GNU
2690 @deftypevr Macro int O_IGNORE_CTTY
2691 Do not recognize the named file as the controlling terminal, even if it
2692 refers to the process's existing controlling terminal device.  Operations
2693 on the new file descriptor will never induce job control signals.
2694 @xref{Job Control}.
2695 @end deftypevr
2696
2697 @comment fcntl.h
2698 @comment GNU
2699 @deftypevr Macro int O_NOLINK
2700 If the named file is a symbolic link, open the link itself instead of
2701 the file it refers to.  (@code{fstat} on the new file descriptor will
2702 return the information returned by @code{lstat} on the link's name.)
2703 @cindex symbolic link, opening
2704 @end deftypevr
2705
2706 @comment fcntl.h
2707 @comment GNU
2708 @deftypevr Macro int O_NOTRANS
2709 If the named file is specially translated, do not invoke the translator.
2710 Open the bare file the translator itself sees.
2711 @end deftypevr
2712
2713
2714 The open-time action flags tell @code{open} to do additional operations
2715 which are not really related to opening the file.  The reason to do them
2716 as part of @code{open} instead of in separate calls is that @code{open}
2717 can do them @i{atomically}.
2718
2719 @comment fcntl.h
2720 @comment POSIX.1
2721 @deftypevr Macro int O_TRUNC
2722 Truncate the file to zero length.  This option is only useful for
2723 regular files, not special files such as directories or FIFOs.  POSIX.1
2724 requires that you open the file for writing to use @code{O_TRUNC}.  In
2725 BSD and GNU you must have permission to write the file to truncate it,
2726 but you need not open for write access.
2727
2728 This is the only open-time action flag specified by POSIX.1.  There is
2729 no good reason for truncation to be done by @code{open}, instead of by
2730 calling @code{ftruncate} afterwards.  The @code{O_TRUNC} flag existed in
2731 Unix before @code{ftruncate} was invented, and is retained for backward
2732 compatibility.
2733 @end deftypevr
2734
2735 @comment fcntl.h
2736 @comment BSD
2737 @deftypevr Macro int O_SHLOCK
2738 Acquire a shared lock on the file, as with @code{flock}.
2739 @xref{File Locks}.
2740
2741 If @code{O_CREAT} is specified, the locking is done atomically when
2742 creating the file.  You are guaranteed that no other process will get
2743 the lock on the new file first.
2744 @end deftypevr
2745
2746 @comment fcntl.h
2747 @comment BSD
2748 @deftypevr Macro int O_EXLOCK
2749 Acquire an exclusive lock on the file, as with @code{flock}.
2750 @xref{File Locks}.  This is atomic like @code{O_SHLOCK}.
2751 @end deftypevr
2752
2753 @node Operating Modes
2754 @subsection I/O Operating Modes
2755
2756 The operating modes affect how input and output operations using a file
2757 descriptor work.  These flags are set by @code{open} and can be fetched
2758 and changed with @code{fcntl}.
2759
2760 @comment fcntl.h
2761 @comment POSIX.1
2762 @deftypevr Macro int O_APPEND
2763 The bit that enables append mode for the file.  If set, then all
2764 @code{write} operations write the data at the end of the file, extending
2765 it, regardless of the current file position.  This is the only reliable
2766 way to append to a file.  In append mode, you are guaranteed that the
2767 data you write will always go to the current end of the file, regardless
2768 of other processes writing to the file.  Conversely, if you simply set
2769 the file position to the end of file and write, then another process can
2770 extend the file after you set the file position but before you write,
2771 resulting in your data appearing someplace before the real end of file.
2772 @end deftypevr
2773
2774 @comment fcntl.h
2775 @comment POSIX.1
2776 @deftypevr Macro int O_NONBLOCK
2777 The bit that enables nonblocking mode for the file.  If this bit is set,
2778 @code{read} requests on the file can return immediately with a failure
2779 status if there is no input immediately available, instead of blocking.
2780 Likewise, @code{write} requests can also return immediately with a
2781 failure status if the output can't be written immediately.
2782
2783 Note that the @code{O_NONBLOCK} flag is overloaded as both an I/O
2784 operating mode and a file name translation flag; @pxref{Open-time Flags}.
2785 @end deftypevr
2786
2787 @comment fcntl.h
2788 @comment BSD
2789 @deftypevr Macro int O_NDELAY
2790 This is an obsolete name for @code{O_NONBLOCK}, provided for
2791 compatibility with BSD.  It is not defined by the POSIX.1 standard.
2792 @end deftypevr
2793
2794 The remaining operating modes are BSD and GNU extensions.  They exist only
2795 on some systems.  On other systems, these macros are not defined.
2796
2797 @comment fcntl.h
2798 @comment BSD
2799 @deftypevr Macro int O_ASYNC
2800 The bit that enables asynchronous input mode.  If set, then @code{SIGIO}
2801 signals will be generated when input is available.  @xref{Interrupt Input}.
2802
2803 Asynchronous input mode is a BSD feature.
2804 @end deftypevr
2805
2806 @comment fcntl.h
2807 @comment BSD
2808 @deftypevr Macro int O_FSYNC
2809 The bit that enables synchronous writing for the file.  If set, each
2810 @code{write} call will make sure the data is reliably stored on disk before
2811 returning. @c !!! xref fsync
2812
2813 Synchronous writing is a BSD feature.
2814 @end deftypevr
2815
2816 @comment fcntl.h
2817 @comment BSD
2818 @deftypevr Macro int O_SYNC
2819 This is another name for @code{O_FSYNC}.  They have the same value.
2820 @end deftypevr
2821
2822 @comment fcntl.h
2823 @comment GNU
2824 @deftypevr Macro int O_NOATIME
2825 If this bit is set, @code{read} will not update the access time of the
2826 file.  @xref{File Times}.  This is used by programs that do backups, so
2827 that backing a file up does not count as reading it.
2828 Only the owner of the file or the superuser may use this bit.
2829
2830 This is a GNU extension.
2831 @end deftypevr
2832
2833 @node Getting File Status Flags
2834 @subsection Getting and Setting File Status Flags
2835
2836 The @code{fcntl} function can fetch or change file status flags.
2837
2838 @comment fcntl.h
2839 @comment POSIX.1
2840 @deftypevr Macro int F_GETFL
2841 This macro is used as the @var{command} argument to @code{fcntl}, to
2842 read the file status flags for the open file with descriptor
2843 @var{filedes}.
2844
2845 The normal return value from @code{fcntl} with this command is a
2846 nonnegative number which can be interpreted as the bitwise OR of the
2847 individual flags.  Since the file access modes are not single-bit values,
2848 you can mask off other bits in the returned flags with @code{O_ACCMODE}
2849 to compare them.
2850
2851 In case of an error, @code{fcntl} returns @code{-1}.  The following
2852 @code{errno} error conditions are defined for this command:
2853
2854 @table @code
2855 @item EBADF
2856 The @var{filedes} argument is invalid.
2857 @end table
2858 @end deftypevr
2859
2860 @comment fcntl.h
2861 @comment POSIX.1
2862 @deftypevr Macro int F_SETFL
2863 This macro is used as the @var{command} argument to @code{fcntl}, to set
2864 the file status flags for the open file corresponding to the
2865 @var{filedes} argument.  This command requires a third @code{int}
2866 argument to specify the new flags, so the call looks like this:
2867
2868 @smallexample
2869 fcntl (@var{filedes}, F_SETFL, @var{new-flags})
2870 @end smallexample
2871
2872 You can't change the access mode for the file in this way; that is,
2873 whether the file descriptor was opened for reading or writing.
2874
2875 The normal return value from @code{fcntl} with this command is an
2876 unspecified value other than @code{-1}, which indicates an error.  The
2877 error conditions are the same as for the @code{F_GETFL} command.
2878 @end deftypevr
2879
2880 If you want to modify the file status flags, you should get the current
2881 flags with @code{F_GETFL} and modify the value.  Don't assume that the
2882 flags listed here are the only ones that are implemented; your program
2883 may be run years from now and more flags may exist then.  For example,
2884 here is a function to set or clear the flag @code{O_NONBLOCK} without
2885 altering any other flags:
2886
2887 @smallexample
2888 @group
2889 /* @r{Set the @code{O_NONBLOCK} flag of @var{desc} if @var{value} is nonzero,}
2890    @r{or clear the flag if @var{value} is 0.}
2891    @r{Return 0 on success, or -1 on error with @code{errno} set.} */
2892
2893 int
2894 set_nonblock_flag (int desc, int value)
2895 @{
2896   int oldflags = fcntl (desc, F_GETFL, 0);
2897   /* @r{If reading the flags failed, return error indication now.} */
2898   if (oldflags == -1)
2899     return -1;
2900   /* @r{Set just the flag we want to set.} */
2901   if (value != 0)
2902     oldflags |= O_NONBLOCK;
2903   else
2904     oldflags &= ~O_NONBLOCK;
2905   /* @r{Store modified flag word in the descriptor.} */
2906   return fcntl (desc, F_SETFL, oldflags);
2907 @}
2908 @end group
2909 @end smallexample
2910
2911 @node File Locks
2912 @section File Locks
2913
2914 @cindex file locks
2915 @cindex record locking
2916 The remaining @code{fcntl} commands are used to support @dfn{record
2917 locking}, which permits multiple cooperating programs to prevent each
2918 other from simultaneously accessing parts of a file in error-prone
2919 ways.
2920
2921 @cindex exclusive lock
2922 @cindex write lock
2923 An @dfn{exclusive} or @dfn{write} lock gives a process exclusive access
2924 for writing to the specified part of the file.  While a write lock is in
2925 place, no other process can lock that part of the file.
2926
2927 @cindex shared lock
2928 @cindex read lock
2929 A @dfn{shared} or @dfn{read} lock prohibits any other process from
2930 requesting a write lock on the specified part of the file.  However,
2931 other processes can request read locks.
2932
2933 The @code{read} and @code{write} functions do not actually check to see
2934 whether there are any locks in place.  If you want to implement a
2935 locking protocol for a file shared by multiple processes, your application
2936 must do explicit @code{fcntl} calls to request and clear locks at the
2937 appropriate points.
2938
2939 Locks are associated with processes.  A process can only have one kind
2940 of lock set for each byte of a given file.  When any file descriptor for
2941 that file is closed by the process, all of the locks that process holds
2942 on that file are released, even if the locks were made using other
2943 descriptors that remain open.  Likewise, locks are released when a
2944 process exits, and are not inherited by child processes created using
2945 @code{fork} (@pxref{Creating a Process}).
2946
2947 When making a lock, use a @code{struct flock} to specify what kind of
2948 lock and where.  This data type and the associated macros for the
2949 @code{fcntl} function are declared in the header file @file{fcntl.h}.
2950 @pindex fcntl.h
2951
2952 @comment fcntl.h
2953 @comment POSIX.1
2954 @deftp {Data Type} {struct flock}
2955 This structure is used with the @code{fcntl} function to describe a file
2956 lock.  It has these members:
2957
2958 @table @code
2959 @item short int l_type
2960 Specifies the type of the lock; one of @code{F_RDLCK}, @code{F_WRLCK}, or
2961 @code{F_UNLCK}.
2962
2963 @item short int l_whence
2964 This corresponds to the @var{whence} argument to @code{fseek} or
2965 @code{lseek}, and specifies what the offset is relative to.  Its value
2966 can be one of @code{SEEK_SET}, @code{SEEK_CUR}, or @code{SEEK_END}.
2967
2968 @item off_t l_start
2969 This specifies the offset of the start of the region to which the lock
2970 applies, and is given in bytes relative to the point specified by
2971 @code{l_whence} member.
2972
2973 @item off_t l_len
2974 This specifies the length of the region to be locked.  A value of
2975 @code{0} is treated specially; it means the region extends to the end of
2976 the file.
2977
2978 @item pid_t l_pid
2979 This field is the process ID (@pxref{Process Creation Concepts}) of the
2980 process holding the lock.  It is filled in by calling @code{fcntl} with
2981 the @code{F_GETLK} command, but is ignored when making a lock.
2982 @end table
2983 @end deftp
2984
2985 @comment fcntl.h
2986 @comment POSIX.1
2987 @deftypevr Macro int F_GETLK
2988 This macro is used as the @var{command} argument to @code{fcntl}, to
2989 specify that it should get information about a lock.  This command
2990 requires a third argument of type @w{@code{struct flock *}} to be passed
2991 to @code{fcntl}, so that the form of the call is:
2992
2993 @smallexample
2994 fcntl (@var{filedes}, F_GETLK, @var{lockp})
2995 @end smallexample
2996
2997 If there is a lock already in place that would block the lock described
2998 by the @var{lockp} argument, information about that lock overwrites
2999 @code{*@var{lockp}}.  Existing locks are not reported if they are
3000 compatible with making a new lock as specified.  Thus, you should
3001 specify a lock type of @code{F_WRLCK} if you want to find out about both
3002 read and write locks, or @code{F_RDLCK} if you want to find out about
3003 write locks only.
3004
3005 There might be more than one lock affecting the region specified by the
3006 @var{lockp} argument, but @code{fcntl} only returns information about
3007 one of them.  The @code{l_whence} member of the @var{lockp} structure is
3008 set to @code{SEEK_SET} and the @code{l_start} and @code{l_len} fields
3009 set to identify the locked region.
3010
3011 If no lock applies, the only change to the @var{lockp} structure is to
3012 update the @code{l_type} to a value of @code{F_UNLCK}.
3013
3014 The normal return value from @code{fcntl} with this command is an
3015 unspecified value other than @code{-1}, which is reserved to indicate an
3016 error.  The following @code{errno} error conditions are defined for
3017 this command:
3018
3019 @table @code
3020 @item EBADF
3021 The @var{filedes} argument is invalid.
3022
3023 @item EINVAL
3024 Either the @var{lockp} argument doesn't specify valid lock information,
3025 or the file associated with @var{filedes} doesn't support locks.
3026 @end table
3027 @end deftypevr
3028
3029 @comment fcntl.h
3030 @comment POSIX.1
3031 @deftypevr Macro int F_SETLK
3032 This macro is used as the @var{command} argument to @code{fcntl}, to
3033 specify that it should set or clear a lock.  This command requires a
3034 third argument of type @w{@code{struct flock *}} to be passed to
3035 @code{fcntl}, so that the form of the call is:
3036
3037 @smallexample
3038 fcntl (@var{filedes}, F_SETLK, @var{lockp})
3039 @end smallexample
3040
3041 If the process already has a lock on any part of the region, the old lock
3042 on that part is replaced with the new lock.  You can remove a lock
3043 by specifying a lock type of @code{F_UNLCK}.
3044
3045 If the lock cannot be set, @code{fcntl} returns immediately with a value
3046 of @code{-1}.  This function does not block waiting for other processes
3047 to release locks.  If @code{fcntl} succeeds, it return a value other
3048 than @code{-1}.
3049
3050 The following @code{errno} error conditions are defined for this
3051 function:
3052
3053 @table @code
3054 @item EAGAIN
3055 @itemx EACCES
3056 The lock cannot be set because it is blocked by an existing lock on the
3057 file.  Some systems use @code{EAGAIN} in this case, and other systems
3058 use @code{EACCES}; your program should treat them alike, after
3059 @code{F_SETLK}.  (The GNU system always uses @code{EAGAIN}.)
3060
3061 @item EBADF
3062 Either: the @var{filedes} argument is invalid; you requested a read lock
3063 but the @var{filedes} is not open for read access; or, you requested a
3064 write lock but the @var{filedes} is not open for write access.
3065
3066 @item EINVAL
3067 Either the @var{lockp} argument doesn't specify valid lock information,
3068 or the file associated with @var{filedes} doesn't support locks.
3069
3070 @item ENOLCK
3071 The system has run out of file lock resources; there are already too
3072 many file locks in place.
3073
3074 Well-designed file systems never report this error, because they have no
3075 limitation on the number of locks.  However, you must still take account
3076 of the possibility of this error, as it could result from network access
3077 to a file system on another machine.
3078 @end table
3079 @end deftypevr
3080
3081 @comment fcntl.h
3082 @comment POSIX.1
3083 @deftypevr Macro int F_SETLKW
3084 This macro is used as the @var{command} argument to @code{fcntl}, to
3085 specify that it should set or clear a lock.  It is just like the
3086 @code{F_SETLK} command, but causes the process to block (or wait)
3087 until the request can be specified.
3088
3089 This command requires a third argument of type @code{struct flock *}, as
3090 for the @code{F_SETLK} command.
3091
3092 The @code{fcntl} return values and errors are the same as for the
3093 @code{F_SETLK} command, but these additional @code{errno} error conditions
3094 are defined for this command:
3095
3096 @table @code
3097 @item EINTR
3098 The function was interrupted by a signal while it was waiting.
3099 @xref{Interrupted Primitives}.
3100
3101 @item EDEADLK
3102 The specified region is being locked by another process.  But that
3103 process is waiting to lock a region which the current process has
3104 locked, so waiting for the lock would result in deadlock.  The system
3105 does not guarantee that it will detect all such conditions, but it lets
3106 you know if it notices one.
3107 @end table
3108 @end deftypevr
3109
3110
3111 The following macros are defined for use as values for the @code{l_type}
3112 member of the @code{flock} structure.  The values are integer constants.
3113
3114 @table @code
3115 @comment fcntl.h
3116 @comment POSIX.1
3117 @vindex F_RDLCK
3118 @item F_RDLCK
3119 This macro is used to specify a read (or shared) lock.
3120
3121 @comment fcntl.h
3122 @comment POSIX.1
3123 @vindex F_WRLCK
3124 @item F_WRLCK
3125 This macro is used to specify a write (or exclusive) lock.
3126
3127 @comment fcntl.h
3128 @comment POSIX.1
3129 @vindex F_UNLCK
3130 @item F_UNLCK
3131 This macro is used to specify that the region is unlocked.
3132 @end table
3133
3134 As an example of a situation where file locking is useful, consider a
3135 program that can be run simultaneously by several different users, that
3136 logs status information to a common file.  One example of such a program
3137 might be a game that uses a file to keep track of high scores.  Another
3138 example might be a program that records usage or accounting information
3139 for billing purposes.
3140
3141 Having multiple copies of the program simultaneously writing to the
3142 file could cause the contents of the file to become mixed up.  But
3143 you can prevent this kind of problem by setting a write lock on the
3144 file before actually writing to the file.
3145
3146 If the program also needs to read the file and wants to make sure that
3147 the contents of the file are in a consistent state, then it can also use
3148 a read lock.  While the read lock is set, no other process can lock
3149 that part of the file for writing.
3150
3151 @c ??? This section could use an example program.
3152
3153 Remember that file locks are only a @emph{voluntary} protocol for
3154 controlling access to a file.  There is still potential for access to
3155 the file by programs that don't use the lock protocol.
3156
3157 @node Interrupt Input
3158 @section Interrupt-Driven Input
3159
3160 @cindex interrupt-driven input
3161 If you set the @code{O_ASYNC} status flag on a file descriptor
3162 (@pxref{File Status Flags}), a @code{SIGIO} signal is sent whenever
3163 input or output becomes possible on that file descriptor.  The process
3164 or process group to receive the signal can be selected by using the
3165 @code{F_SETOWN} command to the @code{fcntl} function.  If the file
3166 descriptor is a socket, this also selects the recipient of @code{SIGURG}
3167 signals that are delivered when out-of-band data arrives on that socket;
3168 see @ref{Out-of-Band Data}.  (@code{SIGURG} is sent in any situation
3169 where @code{select} would report the socket as having an ``exceptional
3170 condition''.  @xref{Waiting for I/O}.)
3171
3172 If the file descriptor corresponds to a terminal device, then @code{SIGIO}
3173 signals are sent to the foreground process group of the terminal.
3174 @xref{Job Control}.
3175
3176 @pindex fcntl.h
3177 The symbols in this section are defined in the header file
3178 @file{fcntl.h}.
3179
3180 @comment fcntl.h
3181 @comment BSD
3182 @deftypevr Macro int F_GETOWN
3183 This macro is used as the @var{command} argument to @code{fcntl}, to
3184 specify that it should get information about the process or process
3185 group to which @code{SIGIO} signals are sent.  (For a terminal, this is
3186 actually the foreground process group ID, which you can get using
3187 @code{tcgetpgrp}; see @ref{Terminal Access Functions}.)
3188
3189 The return value is interpreted as a process ID; if negative, its
3190 absolute value is the process group ID.
3191
3192 The following @code{errno} error condition is defined for this command:
3193
3194 @table @code
3195 @item EBADF
3196 The @var{filedes} argument is invalid.
3197 @end table
3198 @end deftypevr
3199
3200 @comment fcntl.h
3201 @comment BSD
3202 @deftypevr Macro int F_SETOWN
3203 This macro is used as the @var{command} argument to @code{fcntl}, to
3204 specify that it should set the process or process group to which
3205 @code{SIGIO} signals are sent.  This command requires a third argument
3206 of type @code{pid_t} to be passed to @code{fcntl}, so that the form of
3207 the call is:
3208
3209 @smallexample
3210 fcntl (@var{filedes}, F_SETOWN, @var{pid})
3211 @end smallexample
3212
3213 The @var{pid} argument should be a process ID.  You can also pass a
3214 negative number whose absolute value is a process group ID.
3215
3216 The return value from @code{fcntl} with this command is @code{-1}
3217 in case of error and some other value if successful.  The following
3218 @code{errno} error conditions are defined for this command:
3219
3220 @table @code
3221 @item EBADF
3222 The @var{filedes} argument is invalid.
3223
3224 @item ESRCH
3225 There is no process or process group corresponding to @var{pid}.
3226 @end table
3227 @end deftypevr
3228
3229 @c ??? This section could use an example program.