Fcntl.h

Synopsis
int fcntl(int fildes, int cmd, ...);
 * 1) include 
 * 1) include 

Description
The fcntl function shall perform the operations described below on open files. The fildes argument is a file descriptor.

The available values for cmd are defined in  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, arg, taken as an integer of type int. 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 exec functions.

F_GETFD
Get the file descriptor flags defined in  that are associated with the file descriptor fildes. 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 , that are associated with fildes, to the third argument, arg, taken as type int. If the FD_CLOEXEC flag in the third argument is 0, the file shall remain open across the exec functions; otherwise, the file shall be closed upon successful execution of one of the exec functions.

F_GETFL
Get the file status flags and file access modes, defined in , for the file description associated with fildes. The file access modes can be extracted from the return value using the mask O_ACCMODE, which is defined in . 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.

F_SETFL
Set the file status flags, defined in , for the file description associated with fildes from the corresponding bits in the third argument, arg, taken as type int. Bits corresponding to the file access mode and the file creation flags, as defined in , that are set in arg shall be ignored. If any bits in arg other than those mentioned here are changed by the application, the result is unspecified.

F_GETOWN
If fildes 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 fildes does not refer to a socket, the results are unspecified.

F_SETOWN
If fildes 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, arg, taken as type int. Positive values indicate a process ID; negative values, other than -1, indicate a process group ID. If fildes does not refer to a socket, the results are unspecified.

The following values for cmd 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, arg, taken as a pointer to type struct flock, defined in . The information retrieved shall overwrite the information passed to fcntl in the structure flock. 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, arg, taken as a pointer to type struct flock, defined in . 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 . If a shared or exclusive lock cannot be set, fcntl 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 fcntl is waiting for a region, fcntl shall be interrupted. Upon return from the signal handler, fcntl shall return -1 with errno set to [EINTR], and the lock operation shall not be done.

Additional implementation-defined values for cmd may be defined in . 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 flock describes the type ( l_type), starting offset ( l_whence), relative offset ( l_start), size ( l_len), and process ID ( l_pid) of the segment of the file to be affected.

The value of l_whence is SEEK_SET, SEEK_CUR, or SEEK_END, to indicate that the relative offset l_start bytes shall be measured from the start of the file, current position, or end of the file, respectively. The value of l_len is the number of consecutive bytes to be locked. The value of l_len may be negative (where the definition of off_t permits negative values of l_len). The l_pid 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 flock structure shall be as follows:

l_type
Type of blocking lock found.

l_whence
SEEK_SET.

l_start
Start of the blocking lock.

l_len
Length of the blocking lock.

l_pid
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 fcntl function blocks. If the file size or file descriptor seek offset change while fcntl is blocked, this shall not affect the range of bytes locked.

If l_len is positive, the area affected shall start at l_start and end at l_start+ l_len-1. If l_len is negative, the area affected shall start at l_start+ l_len and end at l_start-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_len to 0. If such a lock also has l_start set to 0 and l_whence 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 another process' locked region. If the system detects that sleeping until a locked region is unlocked would cause a deadlock, fcntl shall fail with an [EDEADLK] error.

An unlock (F_UNLCK) request in which l_len is non-zero and the offset of the last byte of the requested segment is the maximum value for an object of type off_t, when the process has an existing lock in which l_len 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_len equal to 0. Otherwise, an unlock (F_UNLCK) request shall attempt to unlock only the requested segment.

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

If fildes refers to a typed memory object, the result of the fcntl function is unspecified.

Return Value
Upon successful completion, the value returned shall depend on cmd as follows:

F_DUPFD
A new file descriptor.

F_GETFD
Value of flags defined in . 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 errno set to indicate the error.

Errors
The fcntl function shall fail if:

EACCES or EAGAIN

The cmd argument is F_SETLK; the type of lock ( l_type) 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.

EBADF
The fildes argument is not a valid open file descriptor, or the argument cmd is F_SETLK or F_SETLKW, the type of lock, l_type, is a shared lock (F_RDLCK), and fildes is not a valid file descriptor open for reading, or the type of lock, l_type, is an exclusive lock (F_WRLCK), and fildes is not a valid file descriptor open for writing.

EINTR
The cmd argument is F_SETLKW and the function was interrupted by a signal.

EINVAL
The cmd argument is invalid, or the cmd argument is F_DUPFD and arg is negative or greater than or equal to {OPEN_MAX}, or the cmd argument is F_GETLK, F_SETLK, or F_SETLKW and the data pointed to by arg is not valid, or fildes refers to a file that does not support locking.

EMFILE
The argument cmd is F_DUPFD and {OPEN_MAX} file descriptors are currently open in the calling process, or no file descriptors greater than or equal to arg are available.

ENOLCK
The argument cmd 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.

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

EOVERFLOW
The cmd argument is F_GETLK, F_SETLK, or F_SETLKW and the smallest or, if l_len is non-zero, the largest offset of any byte in the requested segment cannot be represented correctly in an object of type off_t.

The fcntl function may fail if:

EDEADLK
The cmd 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.

The following sections are informative.

Rationale
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.

The arg 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 IEEE Std 1003.1-2001 are valid. It is a common error to forget this, particularly in the case of F_SETFD.

This volume of IEEE Std 1003.1-2001 permits concurrent read and write access to file data using the fcntl 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 fcntl 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 fcntl works with "any file descriptor associated with that file, however it is obtained", the file descriptor may have been inherited through a fork or exec 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 IEEE Std 1003.1-2001 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 fork, locks are not inherited through fork. Yet locks may be inherited through one of the exec functions.

The identification of a machine in a network environment is outside the scope of this volume of IEEE Std 1003.1-2001. Thus, an l_sysid 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.


 * 1) The relationship to file truncation as supported in 4.2 BSD was not well specified.


 * 1) 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.


 * 1) 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, alarm 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 [EDEADLK] error was made optional.

Code
/* Copyright (C) 1991,1992,1994-2001,2003,2004,2005,2006 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA   02111-1307 USA. */ /* *	POSIX Standard: 6.5 File Control Operations	  */ /* This must be early so  can define types winningly. */ __BEGIN_DECLS /* Get the definitions of O_*, F_*, FD_*: all the numbers and flag bits for `open', `fcntl', et al. */ /* For XPG all symbols from <sys/stat.h> should also be available. */ /* Values for the second argument to access. These may be OR'd together. */ /* XPG wants the following symbols. */ 					  the *at functions should use the current working directory. */ 					  unlinking file. */ 					  effective IDs, not real IDs. */ /* Do the file control operation described by CMD on FD. The remaining arguments are interpreted depending on CMD. This function is a cancellation point and therefore not marked with __THROW. */ extern int fcntl (int __fd, int __cmd, ...); /* Open FILE and return a new file descriptor for it, or -1 on error. OFLAG determines the type of access used. If O_CREAT is on OFLAG, the third argument is taken as a `mode_t', the mode of the created file. This function is a cancellation point and therefore not marked with __THROW. */ extern int open (__const char *__file, int __oflag, ...) __nonnull ((1)); extern int __REDIRECT (open, (__const char *__file, int __oflag, ...), open64) __nonnull ((1)); extern int open64 (__const char *__file, int __oflag, ...) __nonnull ((1)); /* Similar to `open' but a relative path name is interpreted relative to   the directory for which FD is a descriptor. NOTE: some other `openat' implementation support additional functionality through this interface, especially using the O_XATTR flag. This is not yet supported here. This function is a cancellation point and therefore not marked with __THROW. */ extern int openat (int __fd, __const char *__file, int __oflag, ...) __nonnull ((2)); extern int __REDIRECT (openat, (int __fd, __const char *__file, int __oflag, ...), openat64) __nonnull ((2)); extern int openat64 (int __fd, __const char *__file, int __oflag, ...) __nonnull ((2)); /* Create and open FILE, with mode MODE. This takes an `int' MODE argument because that is what `mode_t' will be widened to. This function is a cancellation point and therefore not marked with __THROW. */ extern int creat (__const char *__file, __mode_t __mode) __nonnull ((1)); extern int __REDIRECT (creat, (__const char *__file, __mode_t __mode), 		      creat64) __nonnull ((1)); extern int creat64 (__const char *__file, __mode_t __mode) __nonnull ((1)); && !defined __USE_POSIX)) /* NOTE: These declarations also appear in <unistd.h>; be sure to keep both files consistent. Some systems have them there and some here, and some software depends on the macros being defined without including both. */ /* `lockf' is a simpler interface to the locking facilities of `fcntl'. LEN is always relative to the current file position. The CMD argument is one of the following. */ extern int lockf (int __fd, int __cmd, __off_t __len); extern int __REDIRECT (lockf, (int __fd, int __cmd, __off64_t __len), lockf64); extern int lockf64 (int __fd, int __cmd, __off64_t __len); /* Advice the system about the expected behaviour of the application with respect to the file associated with FD. */ extern int posix_fadvise (int __fd, __off_t __offset, __off_t __len, 			 int __advise) __THROW; extern int __REDIRECT_NTH (posix_fadvise, (int __fd, __off64_t __offset, __off64_t __len, int __advise), 			  posix_fadvise64); extern int posix_fadvise64 (int __fd, __off64_t __offset, __off64_t __len, 			   int __advise) __THROW; /* Reserve storage for the data of the file associated with FD. This function is a possible cancellation points and therefore not marked with __THROW. */ extern int posix_fallocate (int __fd, __off_t __offset, __off_t __len); extern int __REDIRECT (posix_fallocate, (int __fd, __off64_t __offset, __off64_t __len), 		      posix_fallocate64); extern int posix_fallocate64 (int __fd, __off64_t __offset, __off64_t __len); __END_DECLS
 * 1) ifndef	_FCNTL_H
 * 2) define	_FCNTL_H	1
 * 1) include <features.h>
 * 1) include <bits/fcntl.h>
 * 1) ifdef __USE_XOPEN
 * 2) include <sys/stat.h>
 * 3) endif
 * 1) ifdef	__USE_MISC
 * 2) ifndef R_OK			/* Verbatim from <unistd.h>.  Ugh.  */
 * 1)  define R_OK	4		/* Test for read permission.  */
 * 2)  define W_OK	2		/* Test for write permission.  */
 * 3)  define X_OK	1		/* Test for execute permission.  */
 * 4)  define F_OK	0		/* Test for existence.  */
 * 5) endif
 * 6) endif /* Use misc. */
 * 1) ifdef __USE_XOPEN		/* <stdio.h> has the same definitions. */
 * 2) define SEEK_SET	0	/* Seek from beginning of file.  */
 * 3) define SEEK_CUR	1	/* Seek from current position.  */
 * 4) define SEEK_END	2	/* Seek from end of file.  */
 * 5) endif	/* XPG */
 * 1) ifdef __USE_ATFILE
 * 2) define AT_FDCWD		-100	/* Special value used to indicate
 * 1) define AT_SYMLINK_NOFOLLOW	0x100	/* Do not follow symbolic links.  */
 * 2) define AT_REMOVEDIR		0x200	/* Remove directory instead of
 * 1) define AT_SYMLINK_FOLLOW	0x400	/* Follow symbolic links.  */
 * 2) define AT_EACCESS		0x200	/* Test access permitted for
 * 1) endif
 * 1) ifndef __USE_FILE_OFFSET64
 * 1) else
 * 2) ifdef __REDIRECT
 * 1) else
 * 2)  define open open64
 * 3) endif
 * 4) endif
 * 5) ifdef __USE_LARGEFILE64
 * 1) endif
 * 1) ifdef __USE_ATFILE
 * 1) ifndef __USE_FILE_OFFSET64
 * 1) else
 * 2)  ifdef __REDIRECT
 * 1)  else
 * 2)   define openat openat64
 * 3)  endif
 * 4) endif
 * 1) endif
 * 1) ifndef __USE_FILE_OFFSET64
 * 1) else
 * 2) ifdef __REDIRECT
 * 1) else
 * 2)  define creat creat64
 * 3) endif
 * 4) endif
 * 5) ifdef __USE_LARGEFILE64
 * 1) endif
 * 1) if !defined F_LOCK && (defined __USE_MISC || (defined __USE_XOPEN_EXTENDED \
 * 1) define F_ULOCK 0	/* Unlock a previously locked region.  */
 * 2) define F_LOCK  1	/* Lock a region for exclusive use.  */
 * 3) define F_TLOCK 2	/* Test and lock a region for exclusive use.  */
 * 4) define F_TEST  3	/* Test a region for other processes locks.  */
 * 1) ifndef __USE_FILE_OFFSET64
 * 1) else
 * 2) ifdef __REDIRECT
 * 1) else
 * 2)  define lockf lockf64
 * 3) endif
 * 4) endif
 * 5) ifdef __USE_LARGEFILE64
 * 1) endif
 * 2) endif
 * 1) ifdef __USE_XOPEN2K
 * 1) ifndef __USE_FILE_OFFSET64
 * 1) else
 * 2) ifdef __REDIRECT_NTH
 * 1) else
 * 2)  define posix_fadvise posix_fadvise64
 * 3) endif
 * 4) endif
 * 5) ifdef __USE_LARGEFILE64
 * 1) endif
 * 1) ifndef __USE_FILE_OFFSET64
 * 1) else
 * 2) ifdef __REDIRECT
 * 1) else
 * 2)  define posix_fallocate posix_fallocate64
 * 3) endif
 * 4) endif
 * 5) ifdef __USE_LARGEFILE64
 * 1) endif
 * 2) endif
 * 1) endif /* fcntl.h */