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
11

NAME

13       fcntl — file control
14

SYNOPSIS

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

DESCRIPTION

21       The fcntl() function shall perform the operations  described  below  on
22       open files. The fildes argument is a file descriptor.
23
24       The  available  values for cmd are defined in <fcntl.h> and are as fol‐
25       lows:
26
27       F_DUPFD       Return a new file descriptor which shall  be  the  lowest
28                     numbered  available  (that  is,  not  already  open) file
29                     descriptor greater than or equal to the  third  argument,
30                     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 or process
80                     group ID specified to receive SIGURG signals when out-of-
81                     band  data  is  available.  Positive  values  indicate  a
82                     process ID; negative values, other than  −1,  indicate  a
83                     process  group  ID. If fildes does not refer to a socket,
84                     the results are unspecified.
85
86       F_SETOWN      If fildes refers to a socket, set the process or  process
87                     group ID specified to receive SIGURG signals when out-of-
88                     band data is available, using  the  value  of  the  third
89                     argument,  arg, taken as type int.  Positive values indi‐
90                     cate a process ID; negative values, other than −1,  indi‐
91                     cate  a  process  group ID. If fildes does not refer to a
92                     socket, the results are unspecified.
93
94       The following values for cmd are available for advisory record locking.
95       Record  locking  shall  be supported for regular files, and may be sup‐
96       ported for other files.
97
98       F_GETLK       Get the first lock  which  blocks  the  lock  description
99                     pointed to by the third argument, arg, taken as a pointer
100                     to type struct flock, defined in <fcntl.h>.  The informa‐
101                     tion  retrieved shall overwrite the information passed to
102                     fcntl() in the structure flock.  If no lock is found that
103                     would  prevent  this  lock  from  being created, then the
104                     structure shall be left unchanged  except  for  the  lock
105                     type which shall be set to F_UNLCK.
106
107       F_SETLK       Set  or  clear  a file segment lock according to the lock
108                     description pointed to by the third argument, arg,  taken
109                     as  a pointer to type struct flock, defined in <fcntl.h>.
110                     F_SETLK can establish shared (or read) locks (F_RDLCK) or
111                     exclusive  (or  write)  locks  (F_WRLCK),  as  well as to
112                     remove either type of lock (F_UNLCK).  F_RDLCK,  F_WRLCK,
113                     and  F_UNLCK  are  defined  in <fcntl.h>.  If a shared or
114                     exclusive lock cannot be set, fcntl() shall return  imme‐
115                     diately with a return value of −1.
116
117       F_SETLKW      This  command  shall be equivalent to F_SETLK except that
118                     if a shared or exclusive lock is blocked by other  locks,
119                     the thread shall wait until the request can be satisfied.
120                     If a signal that  is  to  be  caught  is  received  while
121                     fcntl()  is waiting for a region, fcntl() shall be inter‐
122                     rupted. Upon return  from  the  signal  handler,  fcntl()
123                     shall  return  −1 with errno set to [EINTR], and the lock
124                     operation shall not be done.
125
126       Additional implementation-defined values for  cmd  may  be  defined  in
127       <fcntl.h>.  Their names shall start with F_.
128
129       When a shared lock is set on a segment of a file, other processes shall
130       be able to set shared locks on that segment  or  a  portion  of  it.  A
131       shared  lock  prevents any other process from setting an exclusive lock
132       on any portion of the protected area. A request for a shared lock shall
133       fail if the file descriptor was not opened with read access.
134
135       An exclusive lock shall prevent any other process from setting a shared
136       lock or an exclusive lock on any  portion  of  the  protected  area.  A
137       request for an exclusive lock shall fail if the file descriptor was not
138       opened with write access.
139
140       The structure  flock  describes  the  type  (l_type),  starting  offset
141       (l_whence),  relative  offset  (l_start),  size (l_len), and process ID
142       (l_pid) of the segment of the file to be affected.
143
144       The value of l_whence is SEEK_SET, SEEK_CUR, or SEEK_END,  to  indicate
145       that the relative offset l_start bytes shall be measured from the start
146       of the file, current position, or end of the  file,  respectively.  The
147       value  of  l_len  is  the number of consecutive bytes to be locked. The
148       value of l_len may be negative (where the definition of  off_t  permits
149       negative  values  of l_len).  The l_pid field is only used with F_GETLK
150       to return the process ID of the process holding a blocking lock.  After
151       a successful F_GETLK request, when a blocking lock is found, the values
152       returned in the flock structure shall be as follows:
153
154       l_type    Type of blocking lock found.
155
156       l_whence  SEEK_SET.
157
158       l_start   Start of the blocking lock.
159
160       l_len     Length of the blocking lock.
161
162       l_pid     Process ID of the process that holds the blocking lock.
163
164       If the command is F_SETLKW  and  the  process  must  wait  for  another
165       process  to  release a lock, then the range of bytes to be locked shall
166       be determined before the fcntl() function blocks. If the file  size  or
167       file descriptor seek offset change while fcntl() is blocked, this shall
168       not affect the range of bytes locked.
169
170       If l_len is positive, the area affected shall start at l_start and  end
171       at  l_start+l_len−1.   If  l_len  is  negative, the area affected shall
172       start at l_start+l_len and end  at  l_start−1.   Locks  may  start  and
173       extend  beyond  the  current end of a file, but shall not extend before
174       the beginning of the file. A lock shall be set to extend to the largest
175       possible  value of the file offset for that file by setting l_len to 0.
176       If such a lock also has l_start  set  to  0  and  l_whence  is  set  to
177       SEEK_SET, the whole file shall be locked.
178
179       There  shall be at most one type of lock set for each byte in the file.
180       Before a successful return from an F_SETLK or an F_SETLKW request  when
181       the  calling  process  has  previously  existing  locks on bytes in the
182       region specified by the request, the previous lock type for  each  byte
183       in  the  specified  region  shall  be replaced by the new lock type. As
184       specified above under the descriptions of shared  locks  and  exclusive
185       locks,  an  F_SETLK or an F_SETLKW request (respectively) shall fail or
186       block when another process has existing locks on bytes in the specified
187       region and the type of any of those locks conflicts with the type spec‐
188       ified in the request.
189
190       All locks associated with a file for a given process shall  be  removed
191       when  a  file descriptor for that file is closed by that process or the
192       process holding that file descriptor terminates. Locks are  not  inher‐
193       ited by a child process.
194
195       A  potential  for  deadlock  occurs  if  a process controlling a locked
196       region is put to sleep by attempting  to  lock  the  locked  region  of
197       another  process.  If  the  system detects that sleeping until a locked
198       region is unlocked would cause a deadlock, fcntl() shall fail  with  an
199       [EDEADLK] error.
200
201       An  unlock  (F_UNLCK) request in which l_len is non-zero and the offset
202       of the last byte of the requested segment is the maximum value  for  an
203       object  of  type  off_t, when the process has an existing lock in which
204       l_len is 0 and which includes the last byte of the  requested  segment,
205       shall be treated as a request to unlock from the start of the requested
206       segment with an l_len  equal  to  0.  Otherwise,  an  unlock  (F_UNLCK)
207       request shall attempt to unlock only the requested segment.
208
209       When  the  file descriptor fildes refers to a shared memory object, the
210       behavior of fcntl() shall be the same as for a regular file except  the
211       effect  of  the following values for the argument cmd shall be unspeci‐
212       fied: F_SETFL, F_GETLK, F_SETLK, and F_SETLKW.
213
214       If fildes refers to a typed memory object, the result  of  the  fcntl()
215       function is unspecified.
216

RETURN VALUE

218       Upon  successful  completion, the value returned shall depend on cmd as
219       follows:
220
221       F_DUPFD     A new file descriptor.
222
223       F_DUPFD_CLOEXEC
224                   A new file descriptor.
225
226       F_GETFD     Value of flags defined  in  <fcntl.h>.   The  return  value
227                   shall not be negative.
228
229       F_SETFD     Value other than −1.
230
231       F_GETFL     Value  of  file  status  flags and access modes. The return
232                   value is not negative.
233
234       F_SETFL     Value other than −1.
235
236       F_GETLK     Value other than −1.
237
238       F_SETLK     Value other than −1.
239
240       F_SETLKW    Value other than −1.
241
242       F_GETOWN    Value of the socket owner process or  process  group;  this
243                   will not be −1.
244
245       F_SETOWN    Value other than −1.
246
247       Otherwise, −1 shall be returned and errno set to indicate the error.
248

ERRORS

250       The fcntl() function shall fail if:
251
252       EACCES or EAGAIN
253              The  cmd  argument  is  F_SETLK;  the type of lock (l_type) is a
254              shared (F_RDLCK) or exclusive (F_WRLCK) lock and the segment  of
255              a  file  to  be  locked  is  already exclusive-locked by another
256              process, or the type is an exclusive lock and  some  portion  of
257              the  segment  of a file to be locked is already shared-locked or
258              exclusive-locked by another process.
259
260       EBADF  The fildes argument is not a valid open file descriptor, or  the
261              argument  cmd  is F_SETLK or F_SETLKW, the type of lock, l_type,
262              is a shared lock (F_RDLCK), and  fildes  is  not  a  valid  file
263              descriptor  open for reading, or the type of lock, l_type, is an
264              exclusive lock  (F_WRLCK),  and  fildes  is  not  a  valid  file
265              descriptor open for writing.
266
267       EINTR  The cmd argument is F_SETLKW and the function was interrupted by
268              a signal.
269
270       EINVAL The cmd argument is invalid, or the cmd argument is  F_DUPFD  or
271              F_DUPFD_CLOEXEC  and arg is negative or greater than or equal to
272              {OPEN_MAX}, or the cmd argument is F_GETLK, F_SETLK, or F_SETLKW
273              and the data pointed to by arg is not valid, or fildes refers to
274              a file that does not support locking.
275
276       EMFILE The argument cmd is F_DUPFD  or  F_DUPFD_CLOEXEC  and  all  file
277              descriptors  available  to the process are currently open, or no
278              file descriptors greater than or equal to arg are available.
279
280       ENOLCK The argument cmd is F_SETLK or F_SETLKW and satisfying the  lock
281              or  unlock  request would result in the number of locked regions
282              in the system exceeding a system-imposed limit.
283
284       EOVERFLOW
285              One of the values to be  returned  cannot  be  represented  cor‐
286              rectly.
287
288       EOVERFLOW
289              The cmd argument is F_GETLK, F_SETLK, or F_SETLKW and the small‐
290              est or, if l_len is non-zero, the largest offset of any byte  in
291              the  requested  segment  cannot  be  represented correctly in an
292              object of type off_t.
293
294       The fcntl() function may fail if:
295
296       EDEADLK
297              The cmd argument is F_SETLKW, the lock is blocked by a lock from
298              another  process,  and  putting  the calling process to sleep to
299              wait for that lock to become free would cause a deadlock.
300
301       The following sections are informative.
302

EXAMPLES

304   Locking and Unlocking a File
305       The following example demonstrates how to place a lock on bytes 100  to
306       109  of  a  file and then later remove it. F_SETLK is used to perform a
307       non-blocking lock request so that the process does not have to wait  if
308       an  incompatible  lock  is held by another process; instead the process
309       can take some other action.
310
311           #include <stdlib.h>
312           #include <unistd.h>
313           #include <fcntl.h>
314           #include <errno.h>
315           #include <stdio.h>
316
317           int
318           main(int argc, char *argv[])
319           {
320               int fd;
321               struct flock fl;
322
323               fd = open("testfile", O_RDWR);
324               if (fd == -1)
325                   /* Handle error */;
326
327               /* Make a non-blocking request to place a write lock
328                  on bytes 100-109 of testfile */
329
330               fl.l_type = F_WRLCK;
331               fl.l_whence = SEEK_SET;
332               fl.l_start = 100;
333               fl.l_len = 10;
334
335               if (fcntl(fd, F_SETLK, &fl) == −1) {
336                   if (errno == EACCES || errno == EAGAIN) {
337                       printf("Already locked by another process\n");
338
339                       /* We can't get the lock at the moment */
340
341                   } else {
342                       /* Handle unexpected error */;
343                   }
344               } else { /* Lock was granted... */
345
346                   /* Perform I/O on bytes 100 to 109 of file */
347
348                   /* Unlock the locked bytes */
349
350                   fl.l_type = F_UNLCK;
351                   fl.l_whence = SEEK_SET;
352                   fl.l_start = 100;
353                   fl.l_len = 10;
354                   if (fcntl(fd, F_SETLK, &fl) == −1)
355                       /* Handle error */;
356               }
357               exit(EXIT_SUCCESS);
358           } /* main */
359
360   Setting the Close-on-Exec Flag
361       The following example demonstrates how to set  the  close-on-exec  flag
362       for the file descriptor fd.
363
364           #include <unistd.h>
365           #include <fcntl.h>
366           ...
367               int flags;
368
369               flags = fcntl(fd, F_GETFD);
370               if (flags == −1)
371                   /* Handle error */;
372               flags |= FD_CLOEXEC;
373               if (fcntl(fd, F_SETFD, flags) == −1)
374                   /* Handle error */;"
375

APPLICATION USAGE

377       The  arg values to F_GETFD, F_SETFD, F_GETFL, and F_SETFL all represent
378       flag values to allow for future growth. Applications using these  func‐
379       tions  should  do  a  read-modify-write  operation on them, rather than
380       assuming that only the values defined by this  volume  of  POSIX.1‐2008
381       are  valid.  It  is  a common error to forget this, particularly in the
382       case of F_SETFD. Some implementations set additional file status  flags
383       to advise the application of default behavior, even though the applica‐
384       tion did not request these flags.
385

RATIONALE

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

FUTURE DIRECTIONS

481       None.
482

SEE ALSO

484       alarm(), close(), exec, open(), sigaction()
485
486       The Base Definitions volume of POSIX.1‐2008, <fcntl.h>, <signal.h>
487
489       Portions  of  this text are reprinted and reproduced in electronic form
490       from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology
491       --  Portable  Operating  System  Interface (POSIX), The Open Group Base
492       Specifications Issue 7, Copyright (C) 2013 by the Institute of Electri‐
493       cal  and  Electronics  Engineers,  Inc  and  The  Open Group.  (This is
494       POSIX.1-2008 with the 2013 Technical Corrigendum  1  applied.)  In  the
495       event of any discrepancy between this version and the original IEEE and
496       The Open Group Standard, the original IEEE and The Open Group  Standard
497       is  the  referee document. The original Standard can be obtained online
498       at http://www.unix.org/online.html .
499
500       Any typographical or formatting errors that appear  in  this  page  are
501       most likely to have been introduced during the conversion of the source
502       files to man page format. To report such errors,  see  https://www.ker
503       nel.org/doc/man-pages/reporting_bugs.html .
504
505
506
507IEEE/The Open Group                  2013                            FCNTL(3P)
Impressum