FCNTL(3)                   POSIX Programmer's Manual                  FCNTL(3)



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


NNAAMMEE
       fcntl -- file control

SSYYNNOOPPSSIISS
       #include <fcntl.h>

       int fcntl(int _f_i_l_d_e_s, int _c_m_d, ...);

DDEESSCCRRIIPPTTIIOONN
       The _f_c_n_t_l() function shall perform the operations described below on
       open files. The _f_i_l_d_e_s argument is a file descriptor.

       The available values for _c_m_d are defined in _<_f_c_n_t_l_._h_> and are as
       follows:

       F_DUPFD       Return a new file descriptor which shall be the lowest
                     numbered available (that is, not already open) file
                     descriptor greater than or equal to the third argument,
                     _a_r_g, taken as an integer of type iinntt.  The new file
                     descriptor shall refer to the same open file description
                     as the original file descriptor, and shall share any
                     locks. The FD_CLOEXEC flag associated with the new file
                     descriptor shall be cleared to keep the file open across
                     calls to one of the _e_x_e_c functions.

       F_DUPFD_CLOEXEC
                     Like F_DUPFD, but the FD_CLOEXEC flag associated with the
                     new file descriptor shall be set.

       F_GETFD       Get the file descriptor flags defined in _<_f_c_n_t_l_._h_> that
                     are associated with the file descriptor _f_i_l_d_e_s.  File
                     descriptor flags are associated with a single file
                     descriptor and do not affect other file descriptors that
                     refer to the same file.

       F_SETFD       Set the file descriptor flags defined in _<_f_c_n_t_l_._h_>, that
                     are associated with _f_i_l_d_e_s, to the third argument, _a_r_g,
                     taken as type iinntt.  If the FD_CLOEXEC flag in the third
                     argument is 0, the file descriptor shall remain open
                     across the _e_x_e_c functions; otherwise, the file descriptor
                     shall be closed upon successful execution of one of the
                     _e_x_e_c functions.

       F_GETFL       Get the file status flags and file access modes, defined
                     in _<_f_c_n_t_l_._h_>, for the file description associated with
                     _f_i_l_d_e_s.  The file access modes can be extracted from the
                     return value using the mask O_ACCMODE, which is defined
                     in _<_f_c_n_t_l_._h_>.  File status flags and file access modes
                     are associated with the file description and do not
                     affect other file descriptors that refer to the same file
                     with different open file descriptions. The flags returned
                     may include non-standard file status flags which the
                     application did not set, provided that these additional
                     flags do not alter the behavior of a conforming
                     application.

       F_SETFL       Set the file status flags, defined in _<_f_c_n_t_l_._h_>, for the
                     file description associated with _f_i_l_d_e_s from the
                     corresponding bits in the third argument, _a_r_g, taken as
                     type iinntt.  Bits corresponding to the file access mode and
                     the file creation flags, as defined in _<_f_c_n_t_l_._h_>, that
                     are set in _a_r_g shall be ignored. If any bits in _a_r_g other
                     than those mentioned here are changed by the application,
                     the result is unspecified. If _f_i_l_d_e_s does not support
                     non-blocking operations, it is unspecified whether the
                     O_NONBLOCK flag will be ignored.

       F_GETOWN      If _f_i_l_d_e_s refers to a socket, get the process or process
                     group ID specified to receive SIGURG signals when out-of-
                     band data is available. Positive values indicate a
                     process ID; negative values, other than -1, indicate a
                     process group ID. If _f_i_l_d_e_s does not refer to a socket,
                     the results are unspecified.

       F_SETOWN      If _f_i_l_d_e_s refers to a socket, set the process or process
                     group ID specified to receive SIGURG signals when out-of-
                     band data is available, using the value of the third
                     argument, _a_r_g, taken as type iinntt.  Positive values
                     indicate a process ID; negative values, other than -1,
                     indicate a process group ID. If _f_i_l_d_e_s does not refer to
                     a socket, the results are unspecified.

       The following values for _c_m_d are available for advisory record locking.
       Record locking shall be supported for regular files, and may be
       supported for other files.

       F_GETLK       Get the first lock which blocks the lock description
                     pointed to by the third argument, _a_r_g, taken as a pointer
                     to type ssttrruucctt fflloocckk, defined in _<_f_c_n_t_l_._h_>.  The
                     information retrieved shall overwrite the information
                     passed to _f_c_n_t_l() in the structure fflloocckk.  If no lock is
                     found that would prevent this lock from being created,
                     then the structure shall be left unchanged except for the
                     lock type which shall be set to F_UNLCK.

       F_SETLK       Set or clear a file segment lock according to the lock
                     description pointed to by the third argument, _a_r_g, taken
                     as a pointer to type ssttrruucctt fflloocckk, defined in _<_f_c_n_t_l_._h_>.
                     F_SETLK can establish shared (or read) locks (F_RDLCK) or
                     exclusive (or write) locks (F_WRLCK), as well as to
                     remove either type of lock (F_UNLCK). F_RDLCK, F_WRLCK,
                     and F_UNLCK are defined in _<_f_c_n_t_l_._h_>.  If a shared or
                     exclusive lock cannot be set, _f_c_n_t_l() shall return
                     immediately with a return value of -1.

       F_SETLKW      This command shall be equivalent to F_SETLK except that
                     if a shared or exclusive lock is blocked by other locks,
                     the thread shall wait until the request can be satisfied.
                     If a signal that is to be caught is received while
                     _f_c_n_t_l() is waiting for a region, _f_c_n_t_l() shall be
                     interrupted. Upon return from the signal handler, _f_c_n_t_l()
                     shall return -1 with _e_r_r_n_o set to [[EEIINNTTRR]], and the lock
                     operation shall not be done.

       Additional implementation-defined values for _c_m_d may be defined in
       _<_f_c_n_t_l_._h_>.  Their names shall start with F_.

       When a shared lock is set on a segment of a file, other processes shall
       be able to set shared locks on that segment or a portion of it. A
       shared lock prevents any other process from setting an exclusive lock
       on any portion of the protected area. A request for a shared lock shall
       fail if the file descriptor was not opened with read access.

       An exclusive lock shall prevent any other process from setting a shared
       lock or an exclusive lock on any portion of the protected area. A
       request for an exclusive lock shall fail if the file descriptor was not
       opened with write access.

       The structure fflloocckk describes the type (_l___t_y_p_e), starting offset
       (_l___w_h_e_n_c_e), relative offset (_l___s_t_a_r_t), size (_l___l_e_n), and process ID
       (_l___p_i_d) of the segment of the file to be affected.

       The value of _l___w_h_e_n_c_e is SEEK_SET, SEEK_CUR, or SEEK_END, to indicate
       that the relative offset _l___s_t_a_r_t bytes shall be measured from the start
       of the file, current position, or end of the file, respectively. The
       value of _l___l_e_n is the number of consecutive bytes to be locked. The
       value of _l___l_e_n may be negative (where the definition of ooffff__tt permits
       negative values of _l___l_e_n).  The _l___p_i_d field is only used with F_GETLK
       to return the process ID of the process holding a blocking lock. After
       a successful F_GETLK request, when a blocking lock is found, the values
       returned in the fflloocckk structure shall be as follows:

       _l___t_y_p_e    Type of blocking lock found.

       _l___w_h_e_n_c_e  SEEK_SET.

       _l___s_t_a_r_t   Start of the blocking lock.

       _l___l_e_n     Length of the blocking lock.

       _l___p_i_d     Process ID of the process that holds the blocking lock.

       If the command is F_SETLKW and the process must wait for another
       process to release a lock, then the range of bytes to be locked shall
       be determined before the _f_c_n_t_l() function blocks. If the file size or
       file descriptor seek offset change while _f_c_n_t_l() is blocked, this shall
       not affect the range of bytes locked.

       If _l___l_e_n is positive, the area affected shall start at _l___s_t_a_r_t and end
       at _l___s_t_a_r_t+_l___l_e_n-1.  If _l___l_e_n is negative, the area affected shall
       start at _l___s_t_a_r_t+_l___l_e_n and end at _l___s_t_a_r_t-1.  Locks may start and
       extend beyond the current end of a file, but shall not extend before
       the beginning of the file. A lock shall be set to extend to the largest
       possible value of the file offset for that file by setting _l___l_e_n to 0.
       If such a lock also has _l___s_t_a_r_t set to 0 and _l___w_h_e_n_c_e is set to
       SEEK_SET, the whole file shall be locked.

       There shall be at most one type of lock set for each byte in the file.
       Before a successful return from an F_SETLK or an F_SETLKW request when
       the calling process has previously existing locks on bytes in the
       region specified by the request, the previous lock type for each byte
       in the specified region shall be replaced by the new lock type. As
       specified above under the descriptions of shared locks and exclusive
       locks, an F_SETLK or an F_SETLKW request (respectively) shall fail or
       block when another process has existing locks on bytes in the specified
       region and the type of any of those locks conflicts with the type
       specified in the request.

       All locks associated with a file for a given process shall be removed
       when a file descriptor for that file is closed by that process or the
       process holding that file descriptor terminates. Locks are not
       inherited by a child process.

       A potential for deadlock occurs if a process controlling a locked
       region is put to sleep by attempting to lock the locked region of
       another process. If the system detects that sleeping until a locked
       region is unlocked would cause a deadlock, _f_c_n_t_l() shall fail with an
       [[EEDDEEAADDLLKK]] error.

       An unlock (F_UNLCK) request in which _l___l_e_n is non-zero and the offset
       of the last byte of the requested segment is the maximum value for an
       object of type ooffff__tt, when the process has an existing lock in which
       _l___l_e_n is 0 and which includes the last byte of the requested segment,
       shall be treated as a request to unlock from the start of the requested
       segment with an _l___l_e_n equal to 0. Otherwise, an unlock (F_UNLCK)
       request shall attempt to unlock only the requested segment.

       When the file descriptor _f_i_l_d_e_s refers to a shared memory object, the
       behavior of _f_c_n_t_l() shall be the same as for a regular file except the
       effect of the following values for the argument _c_m_d shall be
       unspecified: F_SETFL, F_GETLK, F_SETLK, and F_SETLKW.

       If _f_i_l_d_e_s refers to a typed memory object, the result of the _f_c_n_t_l()
       function is unspecified.

RREETTUURRNN VVAALLUUEE
       Upon successful completion, the value returned shall depend on _c_m_d as
       follows:

       F_DUPFD     A new file descriptor.

       F_DUPFD_CLOEXEC
                   A new file descriptor.

       F_GETFD     Value of flags defined in _<_f_c_n_t_l_._h_>.  The return value
                   shall not be negative.

       F_SETFD     Value other than -1.

       F_GETFL     Value of file status flags and access modes. The return
                   value is not negative.

       F_SETFL     Value other than -1.

       F_GETLK     Value other than -1.

       F_SETLK     Value other than -1.

       F_SETLKW    Value other than -1.

       F_GETOWN    Value of the socket owner process or process group; this
                   will not be -1.

       F_SETOWN    Value other than -1.

       Otherwise, -1 shall be returned and _e_r_r_n_o set to indicate the error.

EERRRROORRSS
       The _f_c_n_t_l() function shall fail if:

       EEAACCCCEESS or EEAAGGAAIINN
              The _c_m_d argument is F_SETLK; the type of lock (_l___t_y_p_e) is a
              shared (F_RDLCK) or exclusive (F_WRLCK) lock and the segment of
              a file to be locked is already exclusive-locked by another
              process, or the type is an exclusive lock and some portion of
              the segment of a file to be locked is already shared-locked or
              exclusive-locked by another process.

       EEBBAADDFF  The _f_i_l_d_e_s argument is not a valid open file descriptor, or the
              argument _c_m_d is F_SETLK or F_SETLKW, the type of lock, _l___t_y_p_e,
              is a shared lock (F_RDLCK), and _f_i_l_d_e_s is not a valid file
              descriptor open for reading, or the type of lock, _l___t_y_p_e, is an
              exclusive lock (F_WRLCK), and _f_i_l_d_e_s is not a valid file
              descriptor open for writing.

       EEIINNTTRR  The _c_m_d argument is F_SETLKW and the function was interrupted by
              a signal.

       EEIINNVVAALL The _c_m_d argument is invalid, or the _c_m_d argument is F_DUPFD or
              F_DUPFD_CLOEXEC and _a_r_g is negative or greater than or equal to
              {OPEN_MAX}, or the _c_m_d argument is F_GETLK, F_SETLK, or F_SETLKW
              and the data pointed to by _a_r_g is not valid, or _f_i_l_d_e_s refers to
              a file that does not support locking.

       EEMMFFIILLEE The argument _c_m_d is F_DUPFD or F_DUPFD_CLOEXEC and all file
              descriptors available to the process are currently open, or no
              file descriptors greater than or equal to _a_r_g are available.

       EENNOOLLCCKK The argument _c_m_d is F_SETLK or F_SETLKW and satisfying the lock
              or unlock request would result in the number of locked regions
              in the system exceeding a system-imposed limit.

       EEOOVVEERRFFLLOOWW
              One of the values to be returned cannot be represented
              correctly.

       EEOOVVEERRFFLLOOWW
              The _c_m_d argument is F_GETLK, F_SETLK, or F_SETLKW and the
              smallest or, if _l___l_e_n is non-zero, the largest offset of any
              byte in the requested segment cannot be represented correctly in
              an object of type ooffff__tt.

       The _f_c_n_t_l() function may fail if:

       EEDDEEAADDLLKK
              The _c_m_d argument is F_SETLKW, the lock is blocked by a lock from
              another process, and putting the calling process to sleep to
              wait for that lock to become free would cause a deadlock.

       _T_h_e _f_o_l_l_o_w_i_n_g _s_e_c_t_i_o_n_s _a_r_e _i_n_f_o_r_m_a_t_i_v_e_.

EEXXAAMMPPLLEESS
   LLoocckkiinngg aanndd UUnnlloocckkiinngg aa FFiillee
       The following example demonstrates how to place a lock on bytes 100 to
       109 of a file and then later remove it. F_SETLK is used to perform a
       non-blocking lock request so that the process does not have to wait if
       an incompatible lock is held by another process; instead the process
       can take some other action.

           ##iinncclluuddee <<ssttddlliibb..hh>>
           ##iinncclluuddee <<uunniissttdd..hh>>
           ##iinncclluuddee <<ffccnnttll..hh>>
           ##iinncclluuddee <<eerrrrnnoo..hh>>
           ##iinncclluuddee <<ssttddiioo..hh>>

           int
           main(int argc, char *argv[])
           {
               int fd;
               struct flock fl;

               fd = open("testfile", O_RDWR);
               if (fd == -1)
                   /* Handle error */;

               /* Make a non-blocking request to place a write lock
                  on bytes 100-109 of testfile */

               fl.l_type = F_WRLCK;
               fl.l_whence = SEEK_SET;
               fl.l_start = 100;
               fl.l_len = 10;

               if (fcntl(fd, F_SETLK, &fl) == -1) {
                   if (errno == EACCES || errno == EAGAIN) {
                       printf("Already locked by another process\n");

                       /* We can't get the lock at the moment */

                   } else {
                       /* Handle unexpected error */;
                   }
               } else { /* Lock was granted... */

                   /* Perform I/O on bytes 100 to 109 of file */

                   /* Unlock the locked bytes */

                   fl.l_type = F_UNLCK;
                   fl.l_whence = SEEK_SET;
                   fl.l_start = 100;
                   fl.l_len = 10;
                   if (fcntl(fd, F_SETLK, &fl) == -1)
                       /* Handle error */;
               }
               exit(EXIT_SUCCESS);
           } /* main */

   SSeettttiinngg tthhee CClloossee--oonn--EExxeecc FFllaagg
       The following example demonstrates how to set the close-on-exec flag
       for the file descriptor _f_d.

           ##iinncclluuddee <<uunniissttdd..hh>>
           ##iinncclluuddee <<ffccnnttll..hh>>
           ......
               iinntt ffllaaggss;;

               flags = fcntl(fd, F_GETFD);
               if (flags == -1)
                   /* Handle error */;
               flags |= FD_CLOEXEC;
               if (fcntl(fd, F_SETFD, flags) == -1)
                   /* Handle error */;"

AAPPPPLLIICCAATTIIOONN UUSSAAGGEE
       The _a_r_g values to F_GETFD, F_SETFD, F_GETFL, and F_SETFL all represent
       flag values to allow for future growth. Applications using these
       functions should do a read-modify-write operation on them, rather than
       assuming that only the values defined by this volume of POSIX.1-2008
       are valid. It is a common error to forget this, particularly in the
       case of F_SETFD. Some implementations set additional file status flags
       to advise the application of default behavior, even though the
       application did not request these flags.

RRAATTIIOONNAALLEE
       The ellipsis in the SYNOPSIS is the syntax specified by the ISO C
       standard for a variable number of arguments. It is used because System
       V uses pointers for the implementation of file locking functions.

       This volume of POSIX.1-2008 permits concurrent read and write access to
       file data using the _f_c_n_t_l() function; this is a change from the 1984
       /usr/group standard and early proposals. Without concurrency controls,
       this feature may not be fully utilized without occasional loss of data.

       Data losses occur in several ways. One case occurs when several
       processes try to update the same record, without sequencing controls;
       several updates may occur in parallel and the last writer ``wins''.
       Another case is a bit-tree or other internal list-based database that
       is undergoing reorganization. Without exclusive use to the tree segment
       by the updating process, other reading processes chance getting lost in
       the database when the index blocks are split, condensed, inserted, or
       deleted. While _f_c_n_t_l() is useful for many applications, it is not
       intended to be overly general and does not handle the bit-tree example
       well.

       This facility is only required for regular files because it is not
       appropriate for many devices such as terminals and network connections.

       Since _f_c_n_t_l() works with ``any file descriptor associated with that
       file, however it is obtained'', the file descriptor may have been
       inherited through a _f_o_r_k() or _e_x_e_c operation and thus may affect a file
       that another process also has open.

       The use of the open file description to identify what to lock requires
       extra calls and presents problems if several processes are sharing an
       open file description, but there are too many implementations of the
       existing mechanism for this volume of POSIX.1-2008 to use different
       specifications.

       Another consequence of this model is that closing any file descriptor
       for a given file (whether or not it is the same open file description
       that created the lock) causes the locks on that file to be relinquished
       for that process. Equivalently, any close for any file/process pair
       relinquishes the locks owned on that file for that process. But note
       that while an open file description may be shared through _f_o_r_k(), locks
       are not inherited through _f_o_r_k().  Yet locks may be inherited through
       one of the _e_x_e_c functions.

       The identification of a machine in a network environment is outside the
       scope of this volume of POSIX.1-2008. Thus, an _l___s_y_s_i_d member, such as
       found in System V, is not included in the locking structure.

       Changing of lock types can result in a previously locked region being
       split into smaller regions.

       Mandatory locking was a major feature of the 1984 /usr/group standard.

       For advisory file record locking to be effective, all processes that
       have access to a file must cooperate and use the advisory mechanism
       before doing I/O on the file. Enforcement-mode record locking is
       important when it cannot be assumed that all processes are cooperating.
       For example, if one user uses an editor to update a file at the same
       time that a second user executes another process that updates the same
       file and if only one of the two processes is using advisory locking,
       the processes are not cooperating. Enforcement-mode record locking
       would protect against accidental collisions.

       Secondly, advisory record locking requires a process using locking to
       bracket each I/O operation with lock (or test) and unlock operations.
       With enforcement-mode file and record locking, a process can lock the
       file once and unlock when all I/O operations have been completed.
       Enforcement-mode record locking provides a base that can be enhanced;
       for example, with sharable locks. That is, the mechanism could be
       enhanced to allow a process to lock a file so other processes could
       read it, but none of them could write it.

       Mandatory locks were omitted for several reasons:

        1. Mandatory lock setting was done by multiplexing the set-group-ID
           bit in most implementations; this was confusing, at best.

        2. The relationship to file truncation as supported in 4.2 BSD was not
           well specified.

        3. Any publicly readable file could be locked by anyone. Many
           historical implementations keep the password database in a publicly
           readable file. A malicious user could thus prohibit logins. Another
           possibility would be to hold open a long-distance telephone line.

        4. Some demand-paged historical implementations offer memory mapped
           files, and enforcement cannot be done on that type of file.

       Since sleeping on a region is interrupted with any signal, _a_l_a_r_m() may
       be used to provide a timeout facility in applications requiring it.
       This is useful in deadlock detection. Since implementation of full
       deadlock detection is not always feasible, the [[EEDDEEAADDLLKK]] error was made
       optional.

FFUUTTUURREE DDIIRREECCTTIIOONNSS
       None.

SSEEEE AALLSSOO
       _a_l_a_r_m(), _c_l_o_s_e(), _e_x_e_c, _o_p_e_n(), _s_i_g_a_c_t_i_o_n()

       The Base Definitions volume of POSIX.1-2008, <<ffccnnttll..hh>>, <<ssiiggnnaall..hh>>

CCOOPPYYRRIIGGHHTT
       Portions of this text are reprinted and reproduced in electronic form
       from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology
       -- Portable Operating System Interface (POSIX), The Open Group Base
       Specifications Issue 7, Copyright (C) 2013 by the Institute of
       Electrical and Electronics Engineers, Inc and The Open Group.  (This is
       POSIX.1-2008 with the 2013 Technical Corrigendum 1 applied.) In the
       event of any discrepancy between this version and the original IEEE and
       The Open Group Standard, the original IEEE and The Open Group Standard
       is the referee document. The original Standard can be obtained online
       at http://www.unix.org/online.html .

       Any typographical or formatting errors that appear in this page are
       most likely to have been introduced during the conversion of the source
       files to man page format. To report such errors, see
       https://www.kernel.org/doc/man-pages/reporting_bugs.html .



IEEE/The Open Group                  2013                             FCNTL(3)
