1FCNTL(3P)                  POSIX Programmer's Manual                 FCNTL(3P)
2
3
4

PROLOG

6       This  manual  page is part of the POSIX Programmer's Manual.  The Linux
7       implementation of this interface may differ (consult the  corresponding
8       Linux  manual page for details of Linux behavior), or the interface may
9       not be implemented on Linux.
10

NAME

12       fcntl — file control
13

SYNOPSIS

15       #include <fcntl.h>
16
17       int fcntl(int fildes, int cmd, ...);
18

DESCRIPTION

20       The fcntl() function shall perform the operations  described  below  on
21       open files. The fildes argument is a file descriptor.
22
23       The  available  values for cmd are defined in <fcntl.h> and are as fol‐
24       lows:
25
26       F_DUPFD       Return a new file descriptor which shall be allocated  as
27                     described  in  Section  2.14, File Descriptor Allocation,
28                     except that it shall be  the  lowest  numbered  available
29                     file  descriptor greater than or equal to the third argu‐
30                     ment, arg, taken as an integer of type int.  The new file
31                     descriptor  shall refer to the same open file description
32                     as the original file  descriptor,  and  shall  share  any
33                     locks.  The  FD_CLOEXEC flag associated with the new file
34                     descriptor shall be cleared to keep the file open  across
35                     calls to one of the exec functions.
36
37       F_DUPFD_CLOEXEC
38                     Like F_DUPFD, but the FD_CLOEXEC flag associated with the
39                     new file descriptor shall be set.
40
41       F_GETFD       Get the file descriptor flags defined in  <fcntl.h>  that
42                     are  associated  with  the  file descriptor fildes.  File
43                     descriptor  flags  are  associated  with  a  single  file
44                     descriptor  and do not affect other file descriptors that
45                     refer to the same file.
46
47       F_SETFD       Set the file descriptor flags defined in <fcntl.h>,  that
48                     are  associated  with fildes, to the third argument, arg,
49                     taken as type int.  If the FD_CLOEXEC flag in  the  third
50                     argument  is  0,  the  file  descriptor shall remain open
51                     across the exec functions; otherwise, the file descriptor
52                     shall  be  closed upon successful execution of one of the
53                     exec functions.
54
55       F_GETFL       Get the file status flags and file access modes,  defined
56                     in  <fcntl.h>,  for  the file description associated with
57                     fildes.  The file access modes can be extracted from  the
58                     return  value  using the mask O_ACCMODE, which is defined
59                     in <fcntl.h>.  File status flags and  file  access  modes
60                     are  associated  with  the  file  description  and do not
61                     affect other file descriptors that refer to the same file
62                     with different open file descriptions. The flags returned
63                     may include non-standard  file  status  flags  which  the
64                     application  did  not set, provided that these additional
65                     flags do not alter the behavior of a conforming  applica‐
66                     tion.
67
68       F_SETFL       Set  the file status flags, defined in <fcntl.h>, for the
69                     file description associated with fildes from  the  corre‐
70                     sponding  bits  in the third argument, arg, taken as type
71                     int.  Bits corresponding to the file access mode and  the
72                     file  creation  flags,  as defined in <fcntl.h>, that are
73                     set in arg shall be ignored. If any  bits  in  arg  other
74                     than those mentioned here are changed by the application,
75                     the result is unspecified. If  fildes  does  not  support
76                     non-blocking  operations,  it  is unspecified whether the
77                     O_NONBLOCK flag will be ignored.
78
79       F_GETOWN      If fildes refers to a  socket,  get  the  process  ID  or
80                     process group ID specified to receive SIGURG signals when
81                     out-of-band data  is  available.  Positive  values  shall
82                     indicate  a  process  ID; negative values, other than -1,
83                     shall indicate a process group ID; the value  zero  shall
84                     indicate that no SIGURG signals are to be sent. If fildes
85                     does not refer to a socket, the results are unspecified.
86
87       F_SETOWN      If fildes refers to a  socket,  set  the  process  ID  or
88                     process group ID specified to receive SIGURG signals when
89                     out-of-band data is available, using  the  value  of  the
90                     third  argument, arg, taken as type int.  Positive values
91                     shall indicate a process ID; negative values, other  than
92                     -1,  shall  indicate  a  process group ID; the value zero
93                     shall indicate that no SIGURG signals  are  to  be  sent.
94                     Each  time  a  SIGURG  signal  is  sent  to the specified
95                     process or process group, permission checks equivalent to
96                     those  performed  by  kill()  shall  be  performed, as if
97                     kill() were called by a process with the same  real  user
98                     ID,  effective  user  ID, and privileges that the process
99                     calling fcntl() has at the  time  of  the  call;  if  the
100                     kill()  call  would  fail, no signal shall be sent. These
101                     permission checks may also be performed  by  the  fcntl()
102                     call.  If  the process specified by arg later terminates,
103                     or the process  group  specified  by  arg  later  becomes
104                     empty, while still being specified to receive SIGURG sig‐
105                     nals when out-of-band data is available from fildes, then
106                     no  signals  shall  be  sent  to any subsequently created
107                     process that has the same process ID or process group ID,
108                     regardless  of permission; it is unspecified whether this
109                     is  achieved  by  the  equivalent  of   a   fcntl(fildes,
110                     F_SETOWN,  0)  call at the time the process terminates or
111                     is waited for or the process group becomes empty,  or  by
112                     other  means.  If  fildes does not refer to a socket, the
113                     results are unspecified.
114
115       The following values for cmd are available for advisory record locking.
116       Record  locking  shall  be supported for regular files, and may be sup‐
117       ported for other files.
118
119       F_GETLK       Get any lock which blocks the lock description pointed to
120                     by  the  third  argument, arg, taken as a pointer to type
121                     struct flock,  defined  in  <fcntl.h>.   The  information
122                     retrieved  shall  overwrite  the  information  passed  to
123                     fcntl() in the structure flock.  If no lock is found that
124                     would  prevent  this  lock  from  being created, then the
125                     structure shall be left unchanged  except  for  the  lock
126                     type which shall be set to F_UNLCK.
127
128       F_SETLK       Set  or  clear  a file segment lock according to the lock
129                     description pointed to by the third argument, arg,  taken
130                     as  a pointer to type struct flock, defined in <fcntl.h>.
131                     F_SETLK can establish shared (or read) locks (F_RDLCK) or
132                     exclusive  (or  write)  locks  (F_WRLCK),  as  well as to
133                     remove either type of lock (F_UNLCK).  F_RDLCK,  F_WRLCK,
134                     and  F_UNLCK  are  defined  in <fcntl.h>.  If a shared or
135                     exclusive lock cannot be set, fcntl() shall return  imme‐
136                     diately with a return value of -1.
137
138       F_SETLKW      This  command  shall be equivalent to F_SETLK except that
139                     if a shared or exclusive lock is blocked by other  locks,
140                     the thread shall wait until the request can be satisfied.
141                     If a signal that  is  to  be  caught  is  received  while
142                     fcntl()  is waiting for a region, fcntl() shall be inter‐
143                     rupted. Upon return  from  the  signal  handler,  fcntl()
144                     shall  return  -1 with errno set to [EINTR], and the lock
145                     operation shall not be done.
146
147       Additional implementation-defined values for  cmd  may  be  defined  in
148       <fcntl.h>.  Their names shall start with F_.
149
150       When a shared lock is set on a segment of a file, other processes shall
151       be able to set shared locks on that segment  or  a  portion  of  it.  A
152       shared  lock  prevents any other process from setting an exclusive lock
153       on any portion of the protected area. A request for a shared lock shall
154       fail if the file descriptor was not opened with read access.
155
156       An exclusive lock shall prevent any other process from setting a shared
157       lock or an exclusive lock on any  portion  of  the  protected  area.  A
158       request for an exclusive lock shall fail if the file descriptor was not
159       opened with write access.
160
161       The structure  flock  describes  the  type  (l_type),  starting  offset
162       (l_whence),  relative  offset  (l_start),  size (l_len), and process ID
163       (l_pid) of the segment of the file to be affected.
164
165       The value of l_whence is SEEK_SET, SEEK_CUR, or SEEK_END,  to  indicate
166       that the relative offset l_start bytes shall be measured from the start
167       of the file, current position, or end of the  file,  respectively.  The
168       value  of  l_len  is  the number of consecutive bytes to be locked. The
169       value of l_len may be negative (where the definition of  off_t  permits
170       negative  values  of l_len).  The l_pid field is only used with F_GETLK
171       to return the process ID of the process holding a blocking lock.  After
172       a successful F_GETLK request, when a blocking lock is found, the values
173       returned in the flock structure shall be as follows:
174
175       l_type    Type of blocking lock found.
176
177       l_whence  SEEK_SET.
178
179       l_start   Start of the blocking lock.
180
181       l_len     Length of the blocking lock.
182
183       l_pid     Process ID of the process that holds the blocking lock.
184
185       If the command is F_SETLKW  and  the  process  must  wait  for  another
186       process  to  release a lock, then the range of bytes to be locked shall
187       be determined before the fcntl() function blocks. If the file  size  or
188       file descriptor seek offset change while fcntl() is blocked, this shall
189       not affect the range of bytes locked.
190
191       If l_len is positive, the area affected shall start at l_start and  end
192       at  l_start+l_len-1.   If  l_len  is  negative, the area affected shall
193       start at l_start+l_len and end  at  l_start-1.   Locks  may  start  and
194       extend  beyond  the  current end of a file, but shall not extend before
195       the beginning of the file. A lock shall be set to extend to the largest
196       possible  value of the file offset for that file by setting l_len to 0.
197       If such a lock also has l_start  set  to  0  and  l_whence  is  set  to
198       SEEK_SET, the whole file shall be locked.
199
200       There  shall be at most one type of lock set for each byte in the file.
201       Before a successful return from an F_SETLK or an F_SETLKW request  when
202       the  calling  process  has  previously  existing  locks on bytes in the
203       region specified by the request, the previous lock type for  each  byte
204       in  the  specified  region  shall  be replaced by the new lock type. As
205       specified above under the descriptions of shared  locks  and  exclusive
206       locks,  an  F_SETLK or an F_SETLKW request (respectively) shall fail or
207       block when another process has existing locks on bytes in the specified
208       region and the type of any of those locks conflicts with the type spec‐
209       ified in the request.
210
211       All locks associated with a file for a given process shall  be  removed
212       when  a  file descriptor for that file is closed by that process or the
213       process holding that file descriptor terminates. Locks are  not  inher‐
214       ited by a child process.
215
216       A  potential  for  deadlock  occurs  if  a process controlling a locked
217       region is put to sleep by attempting  to  lock  the  locked  region  of
218       another  process.  If  the  system detects that sleeping until a locked
219       region is unlocked would cause a deadlock, fcntl() shall fail  with  an
220       [EDEADLK] error.
221
222       An  unlock  (F_UNLCK) request in which l_len is non-zero and the offset
223       of the last byte of the requested segment is the maximum value  for  an
224       object  of  type  off_t, when the process has an existing lock in which
225       l_len is 0 and which includes the last byte of the  requested  segment,
226       shall be treated as a request to unlock from the start of the requested
227       segment with an l_len  equal  to  0.  Otherwise,  an  unlock  (F_UNLCK)
228       request shall attempt to unlock only the requested segment.
229
230       When  the  file descriptor fildes refers to a shared memory object, the
231       behavior of fcntl() shall be the same as for a regular file except  the
232       effect  of  the following values for the argument cmd shall be unspeci‐
233       fied: F_SETFL, F_GETLK, F_SETLK, and F_SETLKW.
234
235       If fildes refers to a typed memory object, the result  of  the  fcntl()
236       function is unspecified.
237

RETURN VALUE

239       Upon  successful  completion, the value returned shall depend on cmd as
240       follows:
241
242       F_DUPFD     A new file descriptor.
243
244       F_DUPFD_CLOEXEC
245                   A new file descriptor.
246
247       F_GETFD     Value of flags defined  in  <fcntl.h>.   The  return  value
248                   shall not be negative.
249
250       F_SETFD     Value other than -1.
251
252       F_GETFL     Value  of  file  status  flags and access modes. The return
253                   value is not negative.
254
255       F_SETFL     Value other than -1.
256
257       F_GETLK     Value other than -1.
258
259       F_SETLK     Value other than -1.
260
261       F_SETLKW    Value other than -1.
262
263       F_GETOWN    Value of the socket owner process or  process  group;  this
264                   will not be -1.
265
266       F_SETOWN    Value other than -1.
267
268       Otherwise, -1 shall be returned and errno set to indicate the error.
269

ERRORS

271       The fcntl() function shall fail if:
272
273       EACCES or EAGAIN
274              The  cmd  argument  is  F_SETLK;  the type of lock (l_type) is a
275              shared (F_RDLCK) or exclusive (F_WRLCK) lock and the segment  of
276              a  file  to  be  locked  is  already exclusive-locked by another
277              process, or the type is an exclusive lock and  some  portion  of
278              the  segment  of a file to be locked is already shared-locked or
279              exclusive-locked by another process.
280
281       EBADF  The fildes argument is not a valid open file descriptor, or  the
282              argument  cmd  is F_SETLK or F_SETLKW, the type of lock, l_type,
283              is a shared lock (F_RDLCK), and  fildes  is  not  a  valid  file
284              descriptor  open for reading, or the type of lock, l_type, is an
285              exclusive lock  (F_WRLCK),  and  fildes  is  not  a  valid  file
286              descriptor open for writing.
287
288       EINTR  The cmd argument is F_SETLKW and the function was interrupted by
289              a signal.
290
291       EINVAL The cmd argument is invalid, or the cmd argument is  F_DUPFD  or
292              F_DUPFD_CLOEXEC  and arg is negative or greater than or equal to
293              {OPEN_MAX}, or the cmd argument is F_GETLK, F_SETLK, or F_SETLKW
294              and the data pointed to by arg is not valid, or fildes refers to
295              a file that does not support locking.
296
297       EMFILE The argument cmd is F_DUPFD  or  F_DUPFD_CLOEXEC  and  all  file
298              descriptors  available  to the process are currently open, or no
299              file descriptors greater than or equal to arg are available.
300
301       ENOLCK The argument cmd is F_SETLK or F_SETLKW and satisfying the  lock
302              or  unlock  request would result in the number of locked regions
303              in the system exceeding a system-imposed limit.
304
305       EOVERFLOW
306              One of the values to be  returned  cannot  be  represented  cor‐
307              rectly.
308
309       EOVERFLOW
310              The cmd argument is F_GETLK, F_SETLK, or F_SETLKW and the small‐
311              est or, if l_len is non-zero, the largest offset of any byte  in
312              the  requested  segment  cannot  be  represented correctly in an
313              object of type off_t.
314
315       ESRCH  The cmd argument is F_SETOWN and no process or process group can
316              be found corresponding to that specified by arg.
317
318       The fcntl() function may fail if:
319
320       EDEADLK
321              The cmd argument is F_SETLKW, the lock is blocked by a lock from
322              another process, and putting the calling  process  to  sleep  to
323              wait for that lock to become free would cause a deadlock.
324
325       EINVAL The  cmd  argument  is F_SETOWN and the value of the argument is
326              not valid as a process or process group identifier.
327
328       EPERM  The cmd argument is F_SETOWN and the calling  process  does  not
329              have permission to send a SIGURG signal to any process specified
330              by arg.
331
332       The following sections are informative.
333

EXAMPLES

335   Locking and Unlocking a File
336       The following example demonstrates how to place a lock on bytes 100  to
337       109  of  a  file and then later remove it. F_SETLK is used to perform a
338       non-blocking lock request so that the process does not have to wait  if
339       an  incompatible  lock  is held by another process; instead the process
340       can take some other action.
341
342
343           #include <stdlib.h>
344           #include <unistd.h>
345           #include <fcntl.h>
346           #include <errno.h>
347           #include <stdio.h>
348
349           int
350           main(int argc, char *argv[])
351           {
352               int fd;
353               struct flock fl;
354
355               fd = open("testfile", O_RDWR);
356               if (fd == -1)
357                   /* Handle error */;
358
359               /* Make a non-blocking request to place a write lock
360                  on bytes 100-109 of testfile */
361
362               fl.l_type = F_WRLCK;
363               fl.l_whence = SEEK_SET;
364               fl.l_start = 100;
365               fl.l_len = 10;
366
367               if (fcntl(fd, F_SETLK, &fl) == -1) {
368                   if (errno == EACCES || errno == EAGAIN) {
369                       printf("Already locked by another process\n");
370
371                       /* We cannot get the lock at the moment */
372
373                   } else {
374                       /* Handle unexpected error */;
375                   }
376               } else { /* Lock was granted... */
377
378                   /* Perform I/O on bytes 100 to 109 of file */
379
380                   /* Unlock the locked bytes */
381
382                   fl.l_type = F_UNLCK;
383                   fl.l_whence = SEEK_SET;
384                   fl.l_start = 100;
385                   fl.l_len = 10;
386                   if (fcntl(fd, F_SETLK, &fl) == -1)
387                       /* Handle error */;
388               }
389               exit(EXIT_SUCCESS);
390           } /* main */
391
392   Setting the Close-on-Exec Flag
393       The following example demonstrates how to set  the  close-on-exec  flag
394       for the file descriptor fd.
395
396
397           #include <unistd.h>
398           #include <fcntl.h>
399           ...
400               int flags;
401
402               flags = fcntl(fd, F_GETFD);
403               if (flags == -1)
404                   /* Handle error */;
405               flags |= FD_CLOEXEC;
406               if (fcntl(fd, F_SETFD, flags) == -1)
407                   /* Handle error */;"
408

APPLICATION USAGE

410       The  arg values to F_GETFD, F_SETFD, F_GETFL, and F_SETFL all represent
411       flag values to allow for future growth. Applications using these  func‐
412       tions  should  do  a  read-modify-write  operation on them, rather than
413       assuming that only the values defined by this  volume  of  POSIX.1‐2017
414       are  valid.  It  is  a common error to forget this, particularly in the
415       case of F_SETFD. Some implementations set additional file status  flags
416       to advise the application of default behavior, even though the applica‐
417       tion did not request these flags.
418
419       On systems which do not perform permission checks at  the  time  of  an
420       fcntl()  call  with F_SETOWN, if the permission checks performed at the
421       time the signal is sent disallow sending the signal to any process, the
422       process  that  called  fcntl()  has no way of discovering that this has
423       happened. A call to kill() with signal 0 can be used as a  prior  check
424       of  permissions,  although this is no guarantee that permission will be
425       granted at the time a signal is  sent,  since  the  target  process(es)
426       could change user IDs or privileges in the meantime.
427

RATIONALE

429       The ellipsis in the SYNOPSIS is the syntax specified by the ISO C stan‐
430       dard for a variable number of arguments. It is used  because  System  V
431       uses pointers for the implementation of file locking functions.
432
433       This volume of POSIX.1‐2017 permits concurrent read and write access to
434       file data using the fcntl() function; this is a change  from  the  1984
435       /usr/group  standard and early proposals. Without concurrency controls,
436       this feature may not be fully utilized without occasional loss of data.
437
438       Data losses occur in several ways. One case occurs  when  several  pro‐
439       cesses try to update the same record, without sequencing controls; sev‐
440       eral updates may occur  in  parallel  and  the  last  writer  ``wins''.
441       Another  case  is a bit-tree or other internal list-based database that
442       is undergoing reorganization. Without exclusive use to the tree segment
443       by the updating process, other reading processes chance getting lost in
444       the database when the index blocks are split, condensed,  inserted,  or
445       deleted.  While  fcntl()  is  useful  for  many applications, it is not
446       intended to be overly general and does not handle the bit-tree  example
447       well.
448
449       This  facility  is  only  required  for regular files because it is not
450       appropriate for many devices such as terminals and network connections.
451
452       Since fcntl() works with ``any file  descriptor  associated  with  that
453       file,  however  it  is  obtained'',  the  file descriptor may have been
454       inherited through a fork() or exec operation and thus may affect a file
455       that another process also has open.
456
457       The  use of the open file description to identify what to lock requires
458       extra calls and presents problems if several processes are  sharing  an
459       open  file  description,  but there are too many implementations of the
460       existing mechanism for this volume of  POSIX.1‐2017  to  use  different
461       specifications.
462
463       Another  consequence  of this model is that closing any file descriptor
464       for a given file (whether or not it is the same open  file  description
465       that created the lock) causes the locks on that file to be relinquished
466       for that process. Equivalently, any close  for  any  file/process  pair
467       relinquishes  the  locks  owned on that file for that process. But note
468       that while an open file description may be shared through fork(), locks
469       are  not  inherited through fork().  Yet locks may be inherited through
470       one of the exec functions.
471
472       The identification of a machine in a network environment is outside the
473       scope  of this volume of POSIX.1‐2017. Thus, an l_sysid member, such as
474       found in System V, is not included in the locking structure.
475
476       Changing of lock types can result in a previously locked  region  being
477       split into smaller regions.
478
479       Mandatory locking was a major feature of the 1984 /usr/group standard.
480
481       For  advisory  file  record locking to be effective, all processes that
482       have access to a file must cooperate and  use  the  advisory  mechanism
483       before doing I/O on the file. Enforcement-mode record locking is impor‐
484       tant when it cannot be assumed that all processes are cooperating.  For
485       example,  if  one user uses an editor to update a file at the same time
486       that a second user executes another process that updates the same  file
487       and  if  only  one  of the two processes is using advisory locking, the
488       processes are not cooperating. Enforcement-mode  record  locking  would
489       protect against accidental collisions.
490
491       Secondly,  advisory  record locking requires a process using locking to
492       bracket each I/O operation with lock (or test) and  unlock  operations.
493       With  enforcement-mode  file and record locking, a process can lock the
494       file once and unlock when  all  I/O  operations  have  been  completed.
495       Enforcement-mode  record  locking provides a base that can be enhanced;
496       for example, with sharable locks.  That  is,  the  mechanism  could  be
497       enhanced  to  allow  a  process to lock a file so other processes could
498       read it, but none of them could write it.
499
500       Mandatory locks were omitted for several reasons:
501
502        1. Mandatory lock setting was done by  multiplexing  the  set-group-ID
503           bit in most implementations; this was confusing, at best.
504
505        2. The relationship to file truncation as supported in 4.2 BSD was not
506           well specified.
507
508        3. Any publicly readable file could be locked by anyone. Many histori‐
509           cal  implementations keep the password database in a publicly read‐
510           able file. A malicious user could  thus  prohibit  logins.  Another
511           possibility would be to hold open a long-distance telephone line.
512
513        4. Some  demand-paged  historical  implementations offer memory mapped
514           files, and enforcement cannot be done on that type of file.
515
516       Since sleeping on a region is interrupted with any signal, alarm()  may
517       be  used  to  provide  a timeout facility in applications requiring it.
518       This is useful in deadlock  detection.  Since  implementation  of  full
519       deadlock detection is not always feasible, the [EDEADLK] error was made
520       optional.
521

FUTURE DIRECTIONS

523       None.
524

SEE ALSO

526       alarm(), close(), exec, kill(), open(), sigaction()
527
528       The Base Definitions volume of POSIX.1‐2017, <fcntl.h>, <signal.h>
529
531       Portions of this text are reprinted and reproduced in  electronic  form
532       from  IEEE Std 1003.1-2017, Standard for Information Technology -- Por‐
533       table Operating System Interface (POSIX), The Open Group Base  Specifi‐
534       cations  Issue  7, 2018 Edition, Copyright (C) 2018 by the Institute of
535       Electrical and Electronics Engineers, Inc and The Open Group.   In  the
536       event of any discrepancy between this version and the original IEEE and
537       The Open Group Standard, the original IEEE and The Open Group  Standard
538       is  the  referee document. The original Standard can be obtained online
539       at http://www.opengroup.org/unix/online.html .
540
541       Any typographical or formatting errors that appear  in  this  page  are
542       most likely to have been introduced during the conversion of the source
543       files to man page format. To report such errors,  see  https://www.ker
544       nel.org/doc/man-pages/reporting_bugs.html .
545
546
547
548IEEE/The Open Group                  2017                            FCNTL(3P)
Impressum