1FCNTL(2)                   Linux Programmer's Manual                  FCNTL(2)
2
3
4

NAME

6       fcntl - manipulate file descriptor
7

SYNOPSIS

9       #include <unistd.h>
10       #include <fcntl.h>
11
12       int fcntl(int fd, int cmd);
13       int fcntl(int fd, int cmd, long arg);
14       int fcntl(int fd, int cmd, struct flock *lock);
15

DESCRIPTION

17       fcntl() performs one of the operations described below on the open file
18       descriptor fd.  The operation is determined by cmd.
19
20   Duplicating a file descriptor
21       F_DUPFD
22              Find the lowest numbered available file descriptor greater  than
23              or  equal to arg and make it be a copy of fd.  This is different
24              from dup2(2) which uses exactly the descriptor specified.
25
26              On success, the new descriptor is returned.
27
28              See dup(2) for further details.
29
30   File descriptor flags
31       The following commands manipulate the  flags  associated  with  a  file
32       descriptor.   Currently, only one such flag is defined: FD_CLOEXEC, the
33       close-on-exec flag.  If the FD_CLOEXEC bit is 0,  the  file  descriptor
34       will remain open across an execve(2), otherwise it will be closed.
35
36       F_GETFD
37              Read the file descriptor flags.
38
39       F_SETFD
40              Set the file descriptor flags to the value specified by arg.
41
42   File status flags
43       Each  open  file  description has certain associated status flags, ini‐
44       tialized by open(2) and possibly modified by fcntl(2).  Duplicated file
45       descriptors  (made  with  dup(), fcntl(F_DUPFD), fork(), etc.) refer to
46       the same open file description, and thus share  the  same  file  status
47       flags.
48
49       The file status flags and their semantics are described in open(2).
50
51       F_GETFL
52              Read the file status flags.
53
54       F_SETFL
55              Set  the  file status flags to the value specified by arg.  File
56              access mode (O_RDONLY, O_WRONLY, O_RDWR) and file creation flags
57              (i.e.,  O_CREAT,  O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored.
58              On Linux this command can only  change  the  O_APPEND,  O_ASYNC,
59              O_DIRECT, O_NOATIME, and O_NONBLOCK flags.
60
61   Advisory locking
62       F_GETLK,  F_SETLK  and  F_SETLKW are used to acquire, release, and test
63       for the existence of record locks (also known as file-segment or  file-
64       region  locks).   The  third  argument lock is a pointer to a structure
65       that has at least the following fields (in unspecified order).
66
67         struct flock {
68             ...
69             short l_type;    /* Type of lock: F_RDLCK,
70                                 F_WRLCK, F_UNLCK */
71             short l_whence;  /* How to interpret l_start:
72                                 SEEK_SET, SEEK_CUR, SEEK_END */
73             off_t l_start;   /* Starting offset for lock */
74             off_t l_len;     /* Number of bytes to lock */
75             pid_t l_pid;     /* PID of process blocking our lock
76                                 (F_GETLK only) */
77             ...
78         };
79
80       The l_whence, l_start, and l_len fields of this structure  specify  the
81       range of bytes we wish to lock.  l_start is the starting offset for the
82       lock, and is interpreted relative to either: the start of the file  (if
83       l_whence  is  SEEK_SET);  the  current  file  offset  (if  l_whence  is
84       SEEK_CUR); or the end of the file (if l_whence is  SEEK_END).   In  the
85       final  two  cases, l_start can be a negative number provided the offset
86       does not lie before the start of the file.   l_len  is  a  non-negative
87       integer  (but see the NOTES below) specifying the number of bytes to be
88       locked.  Bytes past the end of the file may be locked,  but  not  bytes
89       before  the  start of the file.  Specifying 0 for l_len has the special
90       meaning: lock all bytes starting at the location specified by  l_whence
91       and  l_start  through  to the end of file, no matter how large the file
92       grows.
93
94       The l_type field can be used to place  a  read  (F_RDLCK)  or  a  write
95       (F_WRLCK) lock on a file.  Any number of processes may hold a read lock
96       (shared lock) on a file region, but only one process may hold  a  write
97       lock (exclusive lock). An exclusive lock excludes all other locks, both
98       shared and exclusive.  A single process can hold only one type of  lock
99       on a file region; if a new lock is applied to an already-locked region,
100       then the existing lock is converted to the new lock type.   (Such  con‐
101       versions may involve splitting, shrinking, or coalescing with an exist‐
102       ing lock if the byte range specified by the new lock does not precisely
103       coincide with the range of the existing lock.)
104
105       F_SETLK
106              Acquire  a lock (when l_type is F_RDLCK or F_WRLCK) or release a
107              lock (when l_type is F_UNLCK) on  the  bytes  specified  by  the
108              l_whence,  l_start,  and l_len fields of lock.  If a conflicting
109              lock is held by another process, this call returns -1  and  sets
110              errno to EACCES or EAGAIN.
111
112       F_SETLKW
113              As  for  F_SETLK, but if a conflicting lock is held on the file,
114              then wait for that lock to be released.  If a signal  is  caught
115              while  waiting, then the call is interrupted and (after the sig‐
116              nal handler has returned) returns immediately (with return value
117              -1 and errno set to EINTR).
118
119       F_GETLK
120              On  input  to  this call, lock describes a lock we would like to
121              place on the file.  If the lock could be  placed,  fcntl()  does
122              not  actually  place it, but returns F_UNLCK in the l_type field
123              of lock and leaves the other fields of the structure  unchanged.
124              If  one or more incompatible locks would prevent this lock being
125              placed, then fcntl() returns details about one of these locks in
126              the l_type, l_whence, l_start, and l_len fields of lock and sets
127              l_pid to be the PID of the process holding that lock.
128
129       In order to place a read lock, fd must be open for reading.   In  order
130       to  place  a  write  lock,  fd must be open for writing.  To place both
131       types of lock, open a file read-write.
132
133       As well as being removed by an explicit F_UNLCK, record locks are auto‐
134       matically released when the process terminates or if it closes any file
135       descriptor referring to a file on which locks are held.  This  is  bad:
136       it  means  that a process can lose the locks on a file like /etc/passwd
137       or /etc/mtab when for some reason a library function decides  to  open,
138       read and close it.
139
140       Record  locks are not inherited by a child created via fork(2), but are
141       preserved across an execve(2).
142
143       Because of the buffering performed by the stdio(3) library, the use  of
144       record  locking  with  routines  in that package should be avoided; use
145       read(2) and write(2) instead.
146
147   Mandatory locking
148       (Non-POSIX.)  The above record locks may be either advisory  or  manda‐
149       tory, and are advisory by default.
150
151       Advisory locks are not enforced and are useful only between cooperating
152       processes.
153
154       Mandatory locks are enforced for all processes.  If a process tries  to
155       perform  an  incompatible  access (e.g., read(2) or write(2)) on a file
156       region that has an incompatible mandatory lock, then the result depends
157       upon  whether the O_NONBLOCK flag is enabled for its open file descrip‐
158       tion.  If the O_NONBLOCK flag is  not  enabled,  then  system  call  is
159       blocked  until  the lock is removed or converted to a mode that is com‐
160       patible with the access.  If the O_NONBLOCK flag is enabled,  then  the
161       system call fails with the error EAGAIN or EWOULDBLOCK.
162
163       To  make use of mandatory locks, mandatory locking must be enabled both
164       on the file system that contains the file to be locked, and on the file
165       itself.   Mandatory  locking  is enabled on a file system using the "-o
166       mand" option to mount(8), or the MS_MANDLOCK flag for mount(2).  Manda‐
167       tory locking is enabled on a file by disabling group execute permission
168       on the file and enabling the set-group-ID permission bit (see  chmod(1)
169       and chmod(2)).
170
171   Managing signals
172       F_GETOWN, F_SETOWN, F_GETSIG and F_SETSIG are used to manage I/O avail‐
173       ability signals:
174
175       F_GETOWN
176              Get the process ID or process group  currently  receiving  SIGIO
177              and  SIGURG  signals  for events on file descriptor fd.  Process
178              IDs are returned as  positive  values;  process  group  IDs  are
179              returned as negative values (but see BUGS below).
180
181       F_SETOWN
182              Set  the  process ID or process group ID that will receive SIGIO
183              and SIGURG signals for events on file descriptor fd.  A  process
184              ID is specified as a positive value; a process group ID is spec‐
185              ified as a negative value.  Most commonly, the  calling  process
186              specifies itself as the owner (that is, arg is specified as get‐
187              pid()).
188
189              If you set the O_ASYNC status flag on a file descriptor  (either
190              by  providing  this  flag with the open(2) call, or by using the
191              F_SETFL command of fcntl()), a SIGIO  signal  is  sent  whenever
192              input  or  output  becomes  possible  on  that  file descriptor.
193              F_SETSIG can be used to obtain delivery of a signal  other  than
194              SIGIO.   If  this  permission  check  fails,  then the signal is
195              silently discarded.
196
197              Sending a signal to  the  owner  process  (group)  specified  by
198              F_SETOWN  is  subject  to  the  same  permissions  checks as are
199              described for kill(2), where the sending process is the one that
200              employs F_SETOWN (but see BUGS below).
201
202              If  the  file  descriptor  fd  refers to a socket, F_SETOWN also
203              selects the recipient of SIGURG signals that are delivered  when
204              out-of-band data arrives on that socket.  (SIGURG is sent in any
205              situation where select(2) would report the socket as  having  an
206              "exceptional condition".)
207
208              If  a  non-zero  value  is given to F_SETSIG in a multi-threaded
209              process running with a threading library  that  supports  thread
210              groups (e.g., NPTL), then a positive value given to F_SETOWN has
211              a different meaning: instead of being a process ID identifying a
212              whole  process,  it is a thread ID identifying a specific thread
213              within a process.  Consequently, it may  be  necessary  to  pass
214              F_SETOWN  the result of gettid() instead of getpid() to get sen‐
215              sible results when F_SETSIG is used.  (In current Linux  thread‐
216              ing  implementations,  a  main thread's thread ID is the same as
217              its process ID.  This means that a single-threaded  program  can
218              equally  use gettid() or getpid() in this scenario.)  Note, how‐
219              ever, that the statements in this paragraph do not apply to  the
220              SIGURG  signal  generated for out-of-band data on a socket: this
221              signal is always sent to either a process or  a  process  group,
222              depending  on the value given to F_SETOWN.  Note also that Linux
223              imposes a limit on the number of real-time signals that  may  be
224              queued to a process (see getrlimit(2) and signal(7)) and if this
225              limit is reached, then the kernel reverts to  delivering  SIGIO,
226              and  this  signal is delivered to the entire process rather than
227              to a specific thread.
228
229       F_GETSIG
230              Get the signal sent when input or output  becomes  possible.   A
231              value  of  zero means SIGIO is sent.  Any other value (including
232              SIGIO) is the signal sent instead, and in this  case  additional
233              info  is  available  to  the  signal  handler  if installed with
234              SA_SIGINFO.
235
236       F_SETSIG
237              Sets the signal sent when input or output becomes  possible.   A
238              value of zero means to send the default SIGIO signal.  Any other
239              value (including SIGIO) is the signal to send  instead,  and  in
240              this  case additional info is available to the signal handler if
241              installed with SA_SIGINFO.
242
243              Additionally, passing a non-zero value to F_SETSIG  changes  the
244              signal  recipient  from  a  whole  process  to a specific thread
245              within a process.  See the  description  of  F_SETOWN  for  more
246              details.
247
248              By  using F_SETSIG with a non-zero value, and setting SA_SIGINFO
249              for the signal handler  (see  sigaction(2)),  extra  information
250              about  I/O events is passed to the handler in a siginfo_t struc‐
251              ture.  If the si_code field indicates the  source  is  SI_SIGIO,
252              the  si_fd  field  gives the file descriptor associated with the
253              event.  Otherwise, there is no indication which file descriptors
254              are pending, and you should use the usual mechanisms (select(2),
255              poll(2), read(2) with O_NONBLOCK set etc.)  to  determine  which
256              file descriptors are available for I/O.
257
258              By  selecting  a  real time signal (value >= SIGRTMIN), multiple
259              I/O events may be queued using the same signal numbers.   (Queu‐
260              ing  is  dependent  on  available memory).  Extra information is
261              available if SA_SIGINFO is set for the signal handler, as above.
262
263       Using these mechanisms, a program can implement fully asynchronous  I/O
264       without using select(2) or poll(2) most of the time.
265
266       The  use  of  O_ASYNC, F_GETOWN, F_SETOWN is specific to BSD and Linux.
267       F_GETSIG and F_SETSIG are Linux specific.  POSIX has  asynchronous  I/O
268       and  the  aio_sigevent  structure  to achieve similar things; these are
269       also available in Linux as part of the GNU C Library (Glibc).
270
271   Leases
272       F_SETLEASE and F_GETLEASE (Linux 2.4 onwards) are  used  (respectively)
273       to  establish and retrieve the current setting of the calling process's
274       lease on the file referred to by fd.  A file lease provides a mechanism
275       whereby  the process holding the lease (the "lease holder") is notified
276       (via delivery of a signal) when a process (the "lease  breaker")  tries
277       to open(2) or truncate(2) that file.
278
279       F_SETLEASE
280              Set  or  remove a file lease according to which of the following
281              values is specified in the integer arg:
282
283
284              F_RDLCK
285                     Take out a read  lease.   This  will  cause  the  calling
286                     process  to be notified when the file is opened for writ‐
287                     ing or is truncated.  A read lease can only be placed  on
288                     a file descriptor that is opened read-only.
289
290              F_WRLCK
291                     Take out a write lease.  This will cause the caller to be
292                     notified when the file is opened for reading  or  writing
293                     or  is  truncated.  A write lease may be placed on a file
294                     only if no other process currently has the file open.
295
296              F_UNLCK
297                     Remove our lease from the file.
298
299       A process may hold only one type of lease on a file.
300
301       Leases may only be taken out on regular files.  An unprivileged process
302       may  only  take out a lease on a file whose UID matches the file system
303       UID of the process.  A process with the CAP_LEASE capability  may  take
304       out leases on arbitrary files.
305
306       F_GETLEASE
307              Indicates  what type of lease we hold on the file referred to by
308              fd by returning either F_RDLCK, F_WRLCK, or F_UNLCK, indicating,
309              respectively, that the calling process holds a read, a write, or
310              no lease on the file.  (The third argument to fcntl()  is  omit‐
311              ted.)
312
313       When  a  process (the "lease breaker") performs an open() or truncate()
314       that conflicts with a lease established via F_SETLEASE, the system call
315       is  blocked  by  the kernel and the kernel notifies the lease holder by
316       sending it a signal  (SIGIO  by  default).   The  lease  holder  should
317       respond to receipt of this signal by doing whatever cleanup is required
318       in preparation for the file to be accessed by  another  process  (e.g.,
319       flushing cached buffers) and then either remove or downgrade its lease.
320       A lease is removed by performing an F_SETLEASE command  specifying  arg
321       as  F_UNLCK.   If  we currently hold a write lease on the file, and the
322       lease breaker is opening the file for reading, then it is sufficient to
323       downgrade  the  lease  to  a read lease.  This is done by performing an
324       F_SETLEASE command specifying arg as F_RDLCK.
325
326       If the lease holder fails to downgrade or remove the lease  within  the
327       number  of  seconds specified in /proc/sys/fs/lease-break-time then the
328       kernel forcibly removes or downgrades the lease holder's lease.
329
330       Once the lease has been voluntarily or forcibly removed or  downgraded,
331       and  assuming  the lease breaker has not unblocked its system call, the
332       kernel permits the lease breaker's system call to proceed.
333
334       If the lease breaker's blocked open() or truncate() is interrupted by a
335       signal  handler,  then  the system call fails with the error EINTR, but
336       the other steps still occur as described above.  If the  lease  breaker
337       is  killed  by a signal while blocked in open() or truncate(), then the
338       other steps still occur as described above.  If the lease breaker spec‐
339       ifies  the  O_NONBLOCK  flag when calling open(), then the call immedi‐
340       ately fails with the error EWOULDBLOCK, but the other steps still occur
341       as described above.
342
343       The  default  signal used to notify the lease holder is SIGIO, but this
344       can be changed using the F_SETSIG command to fcntl().   If  a  F_SETSIG
345       command  is  performed (even one specifying SIGIO), and the signal han‐
346       dler is established using SA_SIGINFO, then the handler will  receive  a
347       siginfo_t structure as its second argument, and the si_fd field of this
348       argument will hold the descriptor of the  leased  file  that  has  been
349       accessed  by  another  process.   (This  is  useful if the caller holds
350       leases against multiple files).
351
352   File and directory change notification (dnotify)
353       F_NOTIFY
354              (Linux 2.4 onwards)  Provide  notification  when  the  directory
355              referred  to  by  fd  or  any  of  the files that it contains is
356              changed.  The events to be notified are specified in arg,  which
357              is  a  bit  mask specified by ORing together zero or more of the
358              following bits:
359
360
361              Bit         Description (event in directory)
362              ─────────────────────────────────────────────────────────────
363              DN_ACCESS   A file was accessed (read, pread, readv)
364              DN_MODIFY   A file was modified (write, pwrite,
365                          writev, truncate, ftruncate)
366              DN_CREATE   A file was created (open, creat, mknod,
367                          mkdir, link, symlink, rename)
368              DN_DELETE   A file was unlinked (unlink, rename to
369                          another directory, rmdir)
370              DN_RENAME   A file was renamed within this
371                          directory (rename)
372              DN_ATTRIB   The attributes of a file were changed
373                          (chown, chmod, utime[s])
374
375              (In order to obtain these definitions, the  _GNU_SOURCE  feature
376              test macro must be defined.)
377
378              Directory  notifications are normally "one-shot", and the appli‐
379              cation  must  re-register  to  receive  further   notifications.
380              Alternatively,  if DN_MULTISHOT is included in arg, then notifi‐
381              cation will remain in effect until explicitly removed.
382
383              A series of F_NOTIFY requests is cumulative, with the events  in
384              arg  being added to the set already monitored.  To disable noti‐
385              fication of all events, make an F_NOTIFY call specifying arg  as
386              0.
387
388              Notification  occurs via delivery of a signal.  The default sig‐
389              nal is SIGIO, but this can be changed using the F_SETSIG command
390              to  fcntl().   In the latter case, the signal handler receives a
391              siginfo_t structure as its second argument (if the  handler  was
392              established using SA_SIGINFO) and the si_fd field of this struc‐
393              ture contains the file descriptor which generated the  notifica‐
394              tion (useful when establishing notification on multiple directo‐
395              ries).
396
397              Especially when using DN_MULTISHOT, a real time signal should be
398              used  for  notification,  so  that multiple notifications can be
399              queued.
400
401              NOTE: New applications should consider using the inotify  inter‐
402              face  (available since kernel 2.6.13), which provides a superior
403              interface for obtaining notifications  of  file  system  events.
404              See inotify(7).
405

RETURN VALUE

407       For a successful call, the return value depends on the operation:
408
409       F_DUPFD  The new descriptor.
410
411       F_GETFD  Value of flags.
412
413       F_GETFL  Value of flags.
414
415       F_GETOWN Value of descriptor owner.
416
417       F_GETSIG Value  of  signal sent when read or write becomes possible, or
418                zero for traditional SIGIO behaviour.
419
420       All other commands
421                Zero.
422
423       On error, -1 is returned, and errno is set appropriately.
424

ERRORS

426       EACCES or EAGAIN
427              Operation is prohibited by locks held by other processes.
428
429       EAGAIN The operation is prohibited because the file  has  been  memory-
430              mapped by another process.
431
432       EBADF  fd is not an open file descriptor, or the command was F_SETLK or
433              F_SETLKW and the file descriptor open mode  doesn't  match  with
434              the type of lock requested.
435
436       EDEADLK
437              It  was detected that the specified F_SETLKW command would cause
438              a deadlock.
439
440       EFAULT lock is outside your accessible address space.
441
442       EINTR  For F_SETLKW, the command was  interrupted  by  a  signal.   For
443              F_GETLK  and  F_SETLK,  the  command was interrupted by a signal
444              before the lock was checked or acquired.  Most likely when lock‐
445              ing  a  remote  file  (e.g. locking over NFS), but can sometimes
446              happen locally.
447
448       EINVAL For F_DUPFD, arg is negative or  is  greater  than  the  maximum
449              allowable  value.   For F_SETSIG, arg is not an allowable signal
450              number.
451
452       EMFILE For F_DUPFD, the process already has the maximum number of  file
453              descriptors open.
454
455       ENOLCK Too  many  segment  locks  open, lock table is full, or a remote
456              locking protocol failed (e.g. locking over NFS).
457
458       EPERM  Attempted to clear the O_APPEND flag on  a  file  that  has  the
459              append-only attribute set.
460

NOTES

462       The  errors  returned  by  dup2()  are different from those returned by
463       F_DUPFD.
464
465       Since kernel 2.0, there is no interaction between  the  types  of  lock
466       placed by flock(2) and fcntl(2).
467
468       POSIX.1-2001  allows  l_len to be negative. (And if it is, the interval
469       described by the lock covers bytes l_start+l_len up  to  and  including
470       l_start-1.)  This is supported by Linux since Linux 2.4.21 and 2.5.49.
471
472       Several systems have more fields in struct flock such as e.g.  l_sysid.
473       Clearly, l_pid alone is not going to be  very  useful  if  the  process
474       holding the lock may live on a different machine.
475

BUGS

477       A limitation of the Linux system call conventions on some architectures
478       (notably x86) means that  if  a  (negative)  process  group  ID  to  be
479       returned  by  F_GETOWN  falls in the range -1 to -4095, then the return
480       value is wrongly interpreted by glibc as an error in the  system  call;
481       that is, the return value of fcntl() will be -1, and errno will contain
482       the (positive) process group ID.
483
484       In Linux 2.4 and earlier, there is bug that can occur when an  unprivi‐
485       leged  process  uses  F_SETOWN  to  specify  the owner of a socket file
486       descriptor as a process (group) other than the caller.  In  this  case,
487       fcntl()  can  return  -1  with  errno set to EPERM, even when the owner
488       process (group) is one that the caller has permission to  send  signals
489       to.   Despite  this error return, the file descriptor owner is set, and
490       signals will be sent to the owner.
491

CONFORMING TO

493       SVr4, 4.3BSD, POSIX.1-2001.   Only  the  operations  F_DUPFD,  F_GETFD,
494       F_SETFD,  F_GETFL,  F_SETFL,  F_GETLK, F_SETLK, F_SETLKW, F_GETOWN, and
495       F_SETOWN are specified in POSIX.1-2001.
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

SEE ALSO

501       dup2(2),  flock(2), open(2), socket(2), lockf(3), capabilities(7), fea‐
502       ture_test_macros(7)
503
504       See    also    locks.txt,    mandatory.txt,    and    dnotify.txt    in
505       /usr/src/linux/Documentation.
506
507
508
509Linux 2.6.14                      2005-05-20                          FCNTL(2)
Impressum