1FCNTL(2) Linux Programmer's Manual FCNTL(2)
2
3
4
6 fcntl - manipulate file descriptor
7
9 #include <unistd.h>
10 #include <fcntl.h>
11
12 int fcntl(int fd, int cmd, ... /* arg */ );
13
15 fcntl() performs one of the operations described below on the open file
16 descriptor fd. The operation is determined by cmd.
17
18 fcntl() can take an optional third argument. Whether or not this argu‐
19 ment is required is determined by cmd. The required argument type is
20 indicated in parentheses after each cmd name (in most cases, the
21 required type is long, and we identify the argument using the name
22 arg), or void is specified if the argument is not required.
23
24 Duplicating a file descriptor
25 F_DUPFD (long)
26 Find the lowest numbered available file descriptor greater than
27 or equal to arg and make it be a copy of fd. This is different
28 from dup2(2), which uses exactly the descriptor specified.
29
30 On success, the new descriptor is returned.
31
32 See dup(2) for further details.
33
34 F_DUPFD_CLOEXEC (long; since Linux 2.6.24)
35 As for F_DUPFD, but additionally set the close-on-exec flag for
36 the duplicate descriptor. Specifying this flag permits a pro‐
37 gram to avoid an additional fcntl() F_SETFD operation to set the
38 FD_CLOEXEC flag. For an explanation of why this flag is useful,
39 see the description of O_CLOEXEC in open(2).
40
41 File descriptor flags
42 The following commands manipulate the flags associated with a file
43 descriptor. Currently, only one such flag is defined: FD_CLOEXEC, the
44 close-on-exec flag. If the FD_CLOEXEC bit is 0, the file descriptor
45 will remain open across an execve(2), otherwise it will be closed.
46
47 F_GETFD (void)
48 Read the file descriptor flags; arg is ignored.
49
50 F_SETFD (long)
51 Set the file descriptor flags to the value specified by arg.
52
53 File status flags
54 Each open file description has certain associated status flags, ini‐
55 tialized by open(2) and possibly modified by fcntl(). Duplicated file
56 descriptors (made with dup(2), fcntl(F_DUPFD), fork(2), etc.) refer to
57 the same open file description, and thus share the same file status
58 flags.
59
60 The file status flags and their semantics are described in open(2).
61
62 F_GETFL (void)
63 Read the file status flags; arg is ignored.
64
65 F_SETFL (long)
66 Set the file status flags to the value specified by arg. File
67 access mode (O_RDONLY, O_WRONLY, O_RDWR) and file creation flags
68 (i.e., O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored.
69 On Linux this command can only change the O_APPEND, O_ASYNC,
70 O_DIRECT, O_NOATIME, and O_NONBLOCK flags.
71
72 Advisory locking
73 F_GETLK, F_SETLK and F_SETLKW are used to acquire, release, and test
74 for the existence of record locks (also known as file-segment or file-
75 region locks). The third argument, lock, is a pointer to a structure
76 that has at least the following fields (in unspecified order).
77
78 struct flock {
79 ...
80 short l_type; /* Type of lock: F_RDLCK,
81 F_WRLCK, F_UNLCK */
82 short l_whence; /* How to interpret l_start:
83 SEEK_SET, SEEK_CUR, SEEK_END */
84 off_t l_start; /* Starting offset for lock */
85 off_t l_len; /* Number of bytes to lock */
86 pid_t l_pid; /* PID of process blocking our lock
87 (F_GETLK only) */
88 ...
89 };
90
91 The l_whence, l_start, and l_len fields of this structure specify the
92 range of bytes we wish to lock. Bytes past the end of the file may be
93 locked, but not bytes before the start of the file.
94
95 l_start is the starting offset for the lock, and is interpreted rela‐
96 tive to either: the start of the file (if l_whence is SEEK_SET); the
97 current file offset (if l_whence is SEEK_CUR); or the end of the file
98 (if l_whence is SEEK_END). In the final two cases, l_start can be a
99 negative number provided the offset does not lie before the start of
100 the file.
101
102 l_len specifies the number of bytes to be locked. If l_len is posi‐
103 tive, then the range to be locked covers bytes l_start up to and
104 including l_start+l_len-1. Specifying 0 for l_len has the special
105 meaning: lock all bytes starting at the location specified by l_whence
106 and l_start through to the end of file, no matter how large the file
107 grows.
108
109 POSIX.1-2001 allows (but does not require) an implementation to support
110 a negative l_len value; if l_len is negative, the interval described by
111 lock covers bytes l_start+l_len up to and including l_start-1. This is
112 supported by Linux since kernel versions 2.4.21 and 2.5.49.
113
114 The l_type field can be used to place a read (F_RDLCK) or a write
115 (F_WRLCK) lock on a file. Any number of processes may hold a read lock
116 (shared lock) on a file region, but only one process may hold a write
117 lock (exclusive lock). An exclusive lock excludes all other locks,
118 both shared and exclusive. A single process can hold only one type of
119 lock on a file region; if a new lock is applied to an already-locked
120 region, then the existing lock is converted to the new lock type.
121 (Such conversions may involve splitting, shrinking, or coalescing with
122 an existing lock if the byte range specified by the new lock does not
123 precisely coincide with the range of the existing lock.)
124
125 F_SETLK (struct flock *)
126 Acquire a lock (when l_type is F_RDLCK or F_WRLCK) or release a
127 lock (when l_type is F_UNLCK) on the bytes specified by the
128 l_whence, l_start, and l_len fields of lock. If a conflicting
129 lock is held by another process, this call returns -1 and sets
130 errno to EACCES or EAGAIN.
131
132 F_SETLKW (struct flock *)
133 As for F_SETLK, but if a conflicting lock is held on the file,
134 then wait for that lock to be released. If a signal is caught
135 while waiting, then the call is interrupted and (after the sig‐
136 nal handler has returned) returns immediately (with return value
137 -1 and errno set to EINTR; see signal(7)).
138
139 F_GETLK (struct flock *)
140 On input to this call, lock describes a lock we would like to
141 place on the file. If the lock could be placed, fcntl() does
142 not actually place it, but returns F_UNLCK in the l_type field
143 of lock and leaves the other fields of the structure unchanged.
144 If one or more incompatible locks would prevent this lock being
145 placed, then fcntl() returns details about one of these locks in
146 the l_type, l_whence, l_start, and l_len fields of lock and sets
147 l_pid to be the PID of the process holding that lock.
148
149 In order to place a read lock, fd must be open for reading. In order
150 to place a write lock, fd must be open for writing. To place both
151 types of lock, open a file read-write.
152
153 As well as being removed by an explicit F_UNLCK, record locks are auto‐
154 matically released when the process terminates or if it closes any file
155 descriptor referring to a file on which locks are held. This is bad:
156 it means that a process can lose the locks on a file like /etc/passwd
157 or /etc/mtab when for some reason a library function decides to open,
158 read and close it.
159
160 Record locks are not inherited by a child created via fork(2), but are
161 preserved across an execve(2).
162
163 Because of the buffering performed by the stdio(3) library, the use of
164 record locking with routines in that package should be avoided; use
165 read(2) and write(2) instead.
166
167 Mandatory locking
168 (Non-POSIX.) The above record locks may be either advisory or manda‐
169 tory, and are advisory by default.
170
171 Advisory locks are not enforced and are useful only between cooperating
172 processes.
173
174 Mandatory locks are enforced for all processes. If a process tries to
175 perform an incompatible access (e.g., read(2) or write(2)) on a file
176 region that has an incompatible mandatory lock, then the result depends
177 upon whether the O_NONBLOCK flag is enabled for its open file descrip‐
178 tion. If the O_NONBLOCK flag is not enabled, then system call is
179 blocked until the lock is removed or converted to a mode that is com‐
180 patible with the access. If the O_NONBLOCK flag is enabled, then the
181 system call fails with the error EAGAIN .
182
183 To make use of mandatory locks, mandatory locking must be enabled both
184 on the file system that contains the file to be locked, and on the file
185 itself. Mandatory locking is enabled on a file system using the "-o
186 mand" option to mount(8), or the MS_MANDLOCK flag for mount(2). Manda‐
187 tory locking is enabled on a file by disabling group execute permission
188 on the file and enabling the set-group-ID permission bit (see chmod(1)
189 and chmod(2)).
190
191 The Linux implementation of mandatory locking is unreliable. See BUGS
192 below.
193
194 Managing signals
195 F_GETOWN, F_SETOWN, F_GETSIG and F_SETSIG are used to manage I/O avail‐
196 ability signals:
197
198 F_GETOWN (void)
199 Return (as the function result) the process ID or process group
200 currently receiving SIGIO and SIGURG signals for events on file
201 descriptor fd. Process IDs are returned as positive values;
202 process group IDs are returned as negative values (but see BUGS
203 below). arg is ignored.
204
205 F_SETOWN (long)
206 Set the process ID or process group ID that will receive SIGIO
207 and SIGURG signals for events on file descriptor fd to the ID
208 given in arg. A process ID is specified as a positive value; a
209 process group ID is specified as a negative value. Most com‐
210 monly, the calling process specifies itself as the owner (that
211 is, arg is specified as getpid(2)).
212
213 If you set the O_ASYNC status flag on a file descriptor by using
214 the F_SETFL command of fcntl(), a SIGIO signal is sent whenever
215 input or output becomes possible on that file descriptor.
216 F_SETSIG can be used to obtain delivery of a signal other than
217 SIGIO. If this permission check fails, then the signal is
218 silently discarded.
219
220 Sending a signal to the owner process (group) specified by
221 F_SETOWN is subject to the same permissions checks as are
222 described for kill(2), where the sending process is the one that
223 employs F_SETOWN (but see BUGS below).
224
225 If the file descriptor fd refers to a socket, F_SETOWN also
226 selects the recipient of SIGURG signals that are delivered when
227 out-of-band data arrives on that socket. (SIGURG is sent in any
228 situation where select(2) would report the socket as having an
229 "exceptional condition".)
230
231 If a non-zero value is given to F_SETSIG in a multithreaded
232 process running with a threading library that supports thread
233 groups (e.g., NPTL), then a positive value given to F_SETOWN has
234 a different meaning: instead of being a process ID identifying a
235 whole process, it is a thread ID identifying a specific thread
236 within a process. Consequently, it may be necessary to pass
237 F_SETOWN the result of gettid(2) instead of getpid(2) to get
238 sensible results when F_SETSIG is used. (In current Linux
239 threading implementations, a main thread's thread ID is the same
240 as its process ID. This means that a single-threaded program
241 can equally use gettid(2) or getpid(2) in this scenario.) Note,
242 however, that the statements in this paragraph do not apply to
243 the SIGURG signal generated for out-of-band data on a socket:
244 this signal is always sent to either a process or a process
245 group, depending on the value given to F_SETOWN. Note also that
246 Linux imposes a limit on the number of real-time signals that
247 may be queued to a process (see getrlimit(2) and signal(7)) and
248 if this limit is reached, then the kernel reverts to delivering
249 SIGIO, and this signal is delivered to the entire process rather
250 than to a specific thread.
251
252 F_GETSIG (void)
253 Return (as the function result) the signal sent when input or
254 output becomes possible. A value of zero means SIGIO is sent.
255 Any other value (including SIGIO) is the signal sent instead,
256 and in this case additional info is available to the signal han‐
257 dler if installed with SA_SIGINFO. arg is ignored.
258
259 F_SETSIG (long)
260 Set the signal sent when input or output becomes possible to the
261 value given in arg. A value of zero means to send the default
262 SIGIO signal. Any other value (including SIGIO) is the signal
263 to send instead, and in this case additional info is available
264 to the signal handler if installed with SA_SIGINFO.
265
266 Additionally, passing a non-zero value to F_SETSIG changes the
267 signal recipient from a whole process to a specific thread
268 within a process. See the description of F_SETOWN for more
269 details.
270
271 By using F_SETSIG with a non-zero value, and setting SA_SIGINFO
272 for the signal handler (see sigaction(2)), extra information
273 about I/O events is passed to the handler in a siginfo_t struc‐
274 ture. If the si_code field indicates the source is SI_SIGIO,
275 the si_fd field gives the file descriptor associated with the
276 event. Otherwise, there is no indication which file descriptors
277 are pending, and you should use the usual mechanisms (select(2),
278 poll(2), read(2) with O_NONBLOCK set etc.) to determine which
279 file descriptors are available for I/O.
280
281 By selecting a real time signal (value >= SIGRTMIN), multiple
282 I/O events may be queued using the same signal numbers. (Queu‐
283 ing is dependent on available memory). Extra information is
284 available if SA_SIGINFO is set for the signal handler, as above.
285
286 Using these mechanisms, a program can implement fully asynchronous I/O
287 without using select(2) or poll(2) most of the time.
288
289 The use of O_ASYNC, F_GETOWN, F_SETOWN is specific to BSD and Linux.
290 F_GETSIG and F_SETSIG are Linux-specific. POSIX has asynchronous I/O
291 and the aio_sigevent structure to achieve similar things; these are
292 also available in Linux as part of the GNU C Library (Glibc).
293
294 Leases
295 F_SETLEASE and F_GETLEASE (Linux 2.4 onwards) are used (respectively)
296 to establish a new lease, and retrieve the current lease, on the open
297 file description referred to by the file descriptor fd. A file lease
298 provides a mechanism whereby the process holding the lease (the "lease
299 holder") is notified (via delivery of a signal) when a process (the
300 "lease breaker") tries to open(2) or truncate(2) the file referred to
301 by that file descriptor.
302
303 F_SETLEASE (long)
304 Set or remove a file lease according to which of the following
305 values is specified in the integer arg:
306
307 F_RDLCK
308 Take out a read lease. This will cause the calling
309 process to be notified when the file is opened for writ‐
310 ing or is truncated. A read lease can only be placed on
311 a file descriptor that is opened read-only.
312
313 F_WRLCK
314 Take out a write lease. This will cause the caller to be
315 notified when the file is opened for reading or writing
316 or is truncated. A write lease may be placed on a file
317 only if there are no other open file descriptors for the
318 file.
319
320 F_UNLCK
321 Remove our lease from the file.
322
323 Leases are associated with an open file description (see open(2)).
324 This means that duplicate file descriptors (created by, for example,
325 fork(2) or dup(2)) refer to the same lease, and this lease may be modi‐
326 fied or released using any of these descriptors. Furthermore, the
327 lease is released by either an explicit F_UNLCK operation on any of
328 these duplicate descriptors, or when all such descriptors have been
329 closed.
330
331 Leases may only be taken out on regular files. An unprivileged process
332 may only take out a lease on a file whose UID (owner) matches the file
333 system UID of the process. A process with the CAP_LEASE capability may
334 take out leases on arbitrary files.
335
336 F_GETLEASE (void)
337 Indicates what type of lease is associated with the file
338 descriptor fd by returning either F_RDLCK, F_WRLCK, or F_UNLCK,
339 indicating, respectively, a read lease , a write lease, or no
340 lease. arg is ignored.
341
342 When a process (the "lease breaker") performs an open(2) or truncate(2)
343 that conflicts with a lease established via F_SETLEASE, the system call
344 is blocked by the kernel and the kernel notifies the lease holder by
345 sending it a signal (SIGIO by default). The lease holder should
346 respond to receipt of this signal by doing whatever cleanup is required
347 in preparation for the file to be accessed by another process (e.g.,
348 flushing cached buffers) and then either remove or downgrade its lease.
349 A lease is removed by performing an F_SETLEASE command specifying arg
350 as F_UNLCK. If the lease holder currently holds a write lease on the
351 file, and the lease breaker is opening the file for reading, then it is
352 sufficient for the lease holder to downgrade the lease to a read lease.
353 This is done by performing an F_SETLEASE command specifying arg as
354 F_RDLCK.
355
356 If the lease holder fails to downgrade or remove the lease within the
357 number of seconds specified in /proc/sys/fs/lease-break-time then the
358 kernel forcibly removes or downgrades the lease holder's lease.
359
360 Once the lease has been voluntarily or forcibly removed or downgraded,
361 and assuming the lease breaker has not unblocked its system call, the
362 kernel permits the lease breaker's system call to proceed.
363
364 If the lease breaker's blocked open(2) or truncate(2) is interrupted by
365 a signal handler, then the system call fails with the error EINTR, but
366 the other steps still occur as described above. If the lease breaker
367 is killed by a signal while blocked in open(2) or truncate(2), then the
368 other steps still occur as described above. If the lease breaker spec‐
369 ifies the O_NONBLOCK flag when calling open(2), then the call immedi‐
370 ately fails with the error EWOULDBLOCK, but the other steps still occur
371 as described above.
372
373 The default signal used to notify the lease holder is SIGIO, but this
374 can be changed using the F_SETSIG command to fcntl(). If a F_SETSIG
375 command is performed (even one specifying SIGIO), and the signal han‐
376 dler is established using SA_SIGINFO, then the handler will receive a
377 siginfo_t structure as its second argument, and the si_fd field of this
378 argument will hold the descriptor of the leased file that has been
379 accessed by another process. (This is useful if the caller holds
380 leases against multiple files).
381
382 File and directory change notification (dnotify)
383 F_NOTIFY (long)
384 (Linux 2.4 onwards) Provide notification when the directory
385 referred to by fd or any of the files that it contains is
386 changed. The events to be notified are specified in arg, which
387 is a bit mask specified by ORing together zero or more of the
388 following bits:
389
390 DN_ACCESS A file was accessed (read, pread, readv)
391 DN_MODIFY A file was modified (write, pwrite, writev, trun‐
392 cate, ftruncate).
393 DN_CREATE A file was created (open, creat, mknod, mkdir, link,
394 symlink, rename).
395 DN_DELETE A file was unlinked (unlink, rename to another
396 directory, rmdir).
397 DN_RENAME A file was renamed within this directory (rename).
398 DN_ATTRIB The attributes of a file were changed (chown, chmod,
399 utime[s]).
400
401 (In order to obtain these definitions, the _GNU_SOURCE feature
402 test macro must be defined.)
403
404 Directory notifications are normally "one-shot", and the appli‐
405 cation must re-register to receive further notifications.
406 Alternatively, if DN_MULTISHOT is included in arg, then notifi‐
407 cation will remain in effect until explicitly removed.
408
409 A series of F_NOTIFY requests is cumulative, with the events in
410 arg being added to the set already monitored. To disable noti‐
411 fication of all events, make an F_NOTIFY call specifying arg as
412 0.
413
414 Notification occurs via delivery of a signal. The default sig‐
415 nal is SIGIO, but this can be changed using the F_SETSIG command
416 to fcntl(). In the latter case, the signal handler receives a
417 siginfo_t structure as its second argument (if the handler was
418 established using SA_SIGINFO) and the si_fd field of this struc‐
419 ture contains the file descriptor which generated the notifica‐
420 tion (useful when establishing notification on multiple directo‐
421 ries).
422
423 Especially when using DN_MULTISHOT, a real time signal should be
424 used for notification, so that multiple notifications can be
425 queued.
426
427 NOTE: New applications should use the inotify interface (avail‐
428 able since kernel 2.6.13), which provides a much superior inter‐
429 face for obtaining notifications of file system events. See
430 inotify(7).
431
433 For a successful call, the return value depends on the operation:
434
435 F_DUPFD The new descriptor.
436
437 F_GETFD Value of flags.
438
439 F_GETFL Value of flags.
440
441 F_GETLEASE
442 Type of lease held on file descriptor.
443
444 F_GETOWN Value of descriptor owner.
445
446 F_GETSIG Value of signal sent when read or write becomes possible, or
447 zero for traditional SIGIO behavior.
448
449 All other commands
450 Zero.
451
452 On error, -1 is returned, and errno is set appropriately.
453
455 EACCES or EAGAIN
456 Operation is prohibited by locks held by other processes.
457
458 EAGAIN The operation is prohibited because the file has been memory-
459 mapped by another process.
460
461 EBADF fd is not an open file descriptor, or the command was F_SETLK or
462 F_SETLKW and the file descriptor open mode doesn't match with
463 the type of lock requested.
464
465 EDEADLK
466 It was detected that the specified F_SETLKW command would cause
467 a deadlock.
468
469 EFAULT lock is outside your accessible address space.
470
471 EINTR For F_SETLKW, the command was interrupted by a signal; see sig‐
472 nal(7). For F_GETLK and F_SETLK, the command was interrupted by
473 a signal before the lock was checked or acquired. Most likely
474 when locking a remote file (e.g., locking over NFS), but can
475 sometimes happen locally.
476
477 EINVAL For F_DUPFD, arg is negative or is greater than the maximum
478 allowable value. For F_SETSIG, arg is not an allowable signal
479 number.
480
481 EMFILE For F_DUPFD, the process already has the maximum number of file
482 descriptors open.
483
484 ENOLCK Too many segment locks open, lock table is full, or a remote
485 locking protocol failed (e.g., locking over NFS).
486
487 EPERM Attempted to clear the O_APPEND flag on a file that has the
488 append-only attribute set.
489
491 SVr4, 4.3BSD, POSIX.1-2001. Only the operations F_DUPFD, F_GETFD,
492 F_SETFD, F_GETFL, F_SETFL, F_GETLK, F_SETLK, F_SETLKW, F_GETOWN, and
493 F_SETOWN are specified in POSIX.1-2001.
494
495 F_DUPFD_CLOEXEC is specified in POSIX.1-2008.
496
497 F_GETSIG, F_SETSIG, F_NOTIFY, F_GETLEASE, and F_SETLEASE are Linux-spe‐
498 cific. (Define the _GNU_SOURCE macro to obtain these definitions.)
499
501 The errors returned by dup2(2) are different from those returned by
502 F_DUPFD.
503
504 Since kernel 2.0, there is no interaction between the types of lock
505 placed by flock(2) and fcntl().
506
507 Several systems have more fields in struct flock such as, for example,
508 l_sysid. Clearly, l_pid alone is not going to be very useful if the
509 process holding the lock may live on a different machine.
510
512 A limitation of the Linux system call conventions on some architectures
513 (notably i386) means that if a (negative) process group ID to be
514 returned by F_GETOWN falls in the range -1 to -4095, then the return
515 value is wrongly interpreted by glibc as an error in the system call;
516 that is, the return value of fcntl() will be -1, and errno will contain
517 the (positive) process group ID.
518
519 In Linux 2.4 and earlier, there is bug that can occur when an unprivi‐
520 leged process uses F_SETOWN to specify the owner of a socket file
521 descriptor as a process (group) other than the caller. In this case,
522 fcntl() can return -1 with errno set to EPERM, even when the owner
523 process (group) is one that the caller has permission to send signals
524 to. Despite this error return, the file descriptor owner is set, and
525 signals will be sent to the owner.
526
527 The implementation of mandatory locking in all known versions of Linux
528 is subject to race conditions which render it unreliable: a write(2)
529 call that overlaps with a lock may modify data after the mandatory lock
530 is acquired; a read(2) call that overlaps with a lock may detect
531 changes to data that were made only after a write lock was acquired.
532 Similar races exist between mandatory locks and mmap(2). It is there‐
533 fore inadvisable to rely on mandatory locking.
534
536 dup2(2), flock(2), open(2), socket(2), lockf(3), capabilities(7), fea‐
537 ture_test_macros(7)
538
539 See also locks.txt, mandatory-locking.txt, and dnotify.txt in the ker‐
540 nel source directory Documentation/filesystems/. (On older kernels,
541 these files are directly under the Documentation/ directory, and manda‐
542 tory-locking.txt is called mandatory.txt.)
543
545 This page is part of release 3.22 of the Linux man-pages project. A
546 description of the project, and information about reporting bugs, can
547 be found at http://www.kernel.org/doc/man-pages/.
548
549
550
551Linux 2009-07-25 FCNTL(2)