fcntl - 操作文件描述符
内容简介
#include <unistd.h> #include <fcntl.h> int fcntl(int fd, int cmd) int fcntl(int fd, int cmd, long arg) int fcntl(int fd, int cmd, struct flock *lock)
描述
fcntl()%uA0执行下述就开文件描述符fd的操作之一。该操作是由 cmd 确定。
复制一个文件描述符
标签 | 描述 |
---|---|
F_DUPFD |
Find the lowest numbered available file descriptor greater than or equal to%uA0arg%uA0and make it be a copy of%uA0fd. This is different fromdup2(2) which uses exactly the descriptor specified.
On success, the new descriptor is returned. See%uA0dup(2) for further details. |
文件描述符标志
The following commands manipulate the flags associated with a file descriptor. Currently, only one such flag is defined:%uA0FD_CLOEXEC, the close-on-exec flag. If theFD_CLOEXEC%uA0bit is 0, the file descriptor will remain open across an%uA0execve(2), otherwise it will be closed.
标签 | 描述 |
---|---|
F_GETFD | Read the file descriptor flags. |
F_SETFD | Set the file descriptor flags to the value specified by%uA0arg. |
文件状态标志
Each open file description has certain associated status flags, initialized by%uA0open(2) and possibly modified by%uA0fcntl(2). Duplicated file descriptors (made with%uA0dup(),fcntl(F_DUPFD),%uA0fork(), etc.) refer to the same open file description, and thus share the same file status flags.
The file status flags and their semantics are described in%uA0open(2).
标签 | 描述 |
---|---|
F_GETFL | Read the file status flags. |
F_SETFL | Set the file status flags to the value specified by%uA0arg. File access mode (O_RDONLY,%uA0O_WRONLY,%uA0O_RDWR) and file creation flags (i.e.,%uA0O_CREAT,%uA0O_EXCL,%uA0O_NOCTTY,%uA0O_TRUNC) in%uA0argare ignored. On Linux this command can only change theO_APPEND,%uA0O_ASYNC,%uA0O_DIRECT,%uA0O_NOATIME, andO_NONBLOCK%uA0flags. |
咨询锁
F_GETLK,%uA0F_SETLK%uA0and%uA0F_SETLKW%uA0are used to acquire, release, and test for the existence of record locks (also known as file-segment or file-region locks). The third argument%uA0lock%uA0is a pointer to a structure that has at least the following fields (in unspecified order).
struct flock { ... short l_type /* Type of lock: F_RDLCK, F_WRLCK, F_UNLCK */ short l_whence /* How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_END */ off_t l_start /* Starting offset for lock */ off_t l_len /* Number of bytes to lock */ pid_t l_pid /* PID of process blocking our lock (F_GETLK only) */ ... }
The%uA0l_whence,%uA0l_start, and%uA0l_len%uA0fields of this structure specify the range of bytes we wish to lock.%uA0l_start%uA0is the starting offset for the lock, and is interpreted relative to either: the start of the file (if%uA0l_whence%uA0is%uA0SEEK_SET) the current file offset (if%uA0l_whenceis%uA0SEEK_CUR) or the end of the file (if%uA0l_whence%uA0is%uA0SEEK_END). In the final two cases,l_startꃊn be a negative number provided the offset does not lie before the start of the file.%uA0l_len%uA0is a non-negative integer (but see the NOTES below) specifying the number of bytes to be locked. Bytes past the end of the file may be locked, but not bytes before the start of the file. Specifying 0 for%uA0l_len%uA0has the special meaning: lock all bytes starting at the location specified by%uA0l_whence%uA0and%uA0l_start%uA0through to the end of file, no matter how large the file grows.
The%uA0l_type%uA0field can be used to place a read (F_RDLCK) or a write (F_WRLCK) lock on a file. Any number of processes may hold a read lock (shared lock) on a file region, but only one process may hold a write lock (exclusive lock). An exclusive lock excludes all other locks, both shared and exclusive. A single process can hold only one type of lock on a file region if a new lock is applied to an already-locked region, then the existing lock is converted to the new lock type. (Such conversions may involve splitting, shrinking, or coalescing with an existing lock if the byte range specified by the new lock does not precisely coincide with the range of the existing lock.)
标签 | 描述 |
---|---|
F_SETLK | Acquire a lock (when%uA0l_type%uA0is%uA0F_RDLCK%uA0or%uA0F_WRLCK) or release a lock (when%uA0l_type%uA0is%uA0F_UNLCK) on the bytes specified by the%uA0l_whence,%uA0l_start, and%uA0l_len%uA0fields of%uA0lock. If a conflicting lock is held by another process, this call returns -1 and setserrno%uA0to%uA0EACCES%uA0or%uA0EAGAIN. |
F_SETLKW | As for%uA0F_SETLK, but if a conflicting lock is held on the file, then wait for that lock to be released. If a signal is caught while waiting, then the call is interrupted and (after the signal handler has returned) returns immediately (with return value -1 anderrno%uA0set to%uA0EINTR). |
F_GETLK | On input to this call,%uA0lockꃞscribes a lock we would like to place on the file. If the lock could be placed,%uA0fcntl() does not actually place it, but returns%uA0F_UNLCK%uA0in the%uA0l_type%uA0field of%uA0lock%uA0and leaves the other fields of the structure unchanged. If one or more incompatible locks would prevent this lock being placed, then%uA0fcntl() returns details about one of these locks in thel_type,%uA0l_whence,%uA0l_start, and%uA0l_len%uA0fields of%uA0lock%uA0and sets%uA0l_pid%uA0to be the PID of the process holding that lock. |
In order to place a read lock,%uA0fd%uA0must be open for reading. In order to place a write lock,fd%uA0must be open for writing. To place both types of lock, open a file read-write.
As well as being removed by an explicit%uA0F_UNLCK, record locks are automatically released when the process terminates or if it closes%uA0any%uA0file descriptor referring to a file on which locks are held. This is bad: it means that a process can lose the locks on a file like%uA0/etc/passwd%uA0or%uA0/etc/mtab%uA0when for some reason a library function decides to open, read and close it.
Record locks are not inherited by a child created via%uA0fork(2), but are preserved across an%uA0execve(2).
Because of the buffering performed by the%uA0stdio(3) library, the use of record locking with routines in that package should be avoided use%uA0read(2) and%uA0write(2) instead.
%uA0
强制锁
(Non-POSIX.) The above record locks may be either advisory or mandatory, and are advisory by default.%uA0
Advisory locks are not enforced and are useful only between cooperating processes.
Mandatory locks are enforced for all processes. If a process tries to perform an incompatible access (e.g.,%uA0read(2) or%uA0write(2)) on a file region that has an incompatible mandatory lock, then the result depends upon whether the%uA0O_NONBLOCK%uA0flag is enabled for its open file description. If the%uA0O_NONBLOCK%uA0flag is not enabled, then system call is blocked until the lock is removed or converted to a mode that is compatible with the access. If the%uA0O_NONBLOCK%uA0flag is enabled, then the system call fails with the error%uA0EAGAIN%uA0or%uA0EWOULDBLOCK.
To make use of mandatory locks, mandatory locking must be enabled both on the file system that contains the file to be locked, and on the file itself. Mandatory locking is enabled on a file system using the "-o mand" option to%uA0mount(8), or theMS_MANDLOCK%uA0flag for%uA0mount(2). Mandatory locking is enabled on a file by disabling group execute permission on the file and enabling the set-group-ID permission bit (seechmod(1) and%uA0chmod(2)).
管理信号
F_GETOWN,%uA0F_SETOWN,%uA0F_GETSIG%uA0and%uA0F_SETSIG%uA0are used to manage I/O availability signals:
标签 | 描述 |
---|---|
F_GETOWN | Get the process ID or process group currently receiving SIGIO and SIGURG signals for events on file descriptor%uA0fd. Process IDs are returned as positive values process group IDs are returned as negative values (but see BUGS below). |
F_SETOWN |
Set the process ID or process group ID that will receive SIGIO and SIGURG signals for events on file descriptor%uA0fd. A process ID is specified as a positive value a process group ID is specified as a negative value. Most commonly, the calling process specifies itself as the owner (that is,%uA0arg%uA0is specified asgetpid()).
If you set the%uA0O_ASYNC%uA0status flag on a file descriptor (either by providing this flag with the%uA0open(2) call, or by using theF_SETFL%uA0command of%uA0fcntl()), a SIGIO signal is sent whenever input or output becomes possible on that file descriptor.F_SETSIGꃊn be used to obtain delivery of a signal other than SIGIO. If this permission check fails, then the signal is silently discarded. Sending a signal to the owner process (group) specified byF_SETOWN%uA0is subject to the same permissions checks as are described for%uA0kill(2), where the sending process is the one that employs%uA0F_SETOWN%uA0(but see BUGS below). If the file descriptor%uA0fd%uA0refers to a socket,%uA0F_SETOWN%uA0also selects the recipient of SIGURG signals that are delivered when out-of-band data arrives on that socket. (SIGURG is sent in any situation where%uA0select(2) would report the socket as having an "exceptional condition".) If a non-zero value is given to%uA0F_SETSIG%uA0in a multi-threaded process running with a threading library that supports thread groups (e.g., NPTL), then a positive value given to%uA0F_SETOWNhas a different meaning: instead of being a process ID identifying a whole process, it is a thread ID identifying a specific thread within a process. Consequently, it may be necessary to pass%uA0F_SETOWN%uA0the result of%uA0gettid() instead ofgetpid() to get sensible results when%uA0F_SETSIG%uA0is used. (In current Linux threading implementations, a main thread’s thread ID is the same as its process ID. This means that a single-threaded program can equally use%uA0gettid() or%uA0getpid() in this scenario.) Note, however, that the statements in this paragraph do not apply to the SIGURG signal generated for out-of-band data on a socket: this signal is always sent to either a process or a process group, depending on the value given toF_SETOWN. Note also that Linux imposes a limit on the number of real-time signals that may be queued to a process (seegetrlimit(2) and%uA0signal(7)) and if this limit is reached, then the kernel reverts to delivering SIGIO, and this signal is delivered to the entire process rather than to a specific thread. |
F_GETSIG | Get the signal sent when input or output becomes possible. A value of zero means SIGIO is sent. Any other value (including SIGIO) is the signal sent instead, and in this case additional info is available to the signal handler if installed with SA_SIGINFO. |
F_SETSIG |
Sets the signal sent when input or output becomes possible. A value of zero means to send the default SIGIO signal. Any other value (including SIGIO) is the signal to send instead, and in this case additional info is available to the signal handler if installed with SA_SIGINFO.
Additionally, passing a non-zero value to%uA0F_SETSIG%uA0changes the signal recipient from a whole process to a specific thread within a process. See the description of%uA0F_SETOWN%uA0for more details. By using%uA0F_SETSIG%uA0with a non-zero value, and setting SA_SIGINFO for the signal handler (see%uA0sigaction(2)), extra information about I/O events is passed to the handler in asiginfo_t%uA0structure. If the%uA0si_code%uA0field indicates the source is SI_SIGIO, the%uA0si_fd%uA0field gives the file descriptor associated with the event. Otherwise, there is no indication which file descriptors are pending, and you should use the usual mechanisms (select(2),%uA0poll(2),%uA0read(2) with%uA0O_NONBLOCK%uA0set etc.) to determine which file descriptors are available for I/O. By selecting a real time signal (value >= SIGRTMIN), multiple I/O events may be queued using the same signal numbers. (Queuing is dependent on available memory). Extra information is available if SA_SIGINFO is set for the signal handler, as above. |
Using these mechanisms, a program can implement fully asynchronous I/O without using%uA0select(2) or%uA0poll(2) most of the time.
The use of%uA0O_ASYNC,%uA0F_GETOWN,%uA0F_SETOWN%uA0is specific to BSD and Linux.%uA0F_GETSIGand%uA0F_SETSIG%uA0are Linux-specific. POSIX has asynchronous I/O and the%uA0aio_sigeventstructure to achieve similar things these are also available in Linux as part of the GNU C Library (Glibc).
%uA0
租约
F_SETLEASE%uA0and%uA0F_GETLEASE%uA0(Linux 2.4 onwards) are used (respectively) to establish and retrieve the current setting of the calling process’s lease on the file referred to byfd. A file lease provides a mechanism whereby the process holding the lease (the "lease holder") is notified (via delivery of a signal) when a process (the "lease breaker") tries to%uA0open(2) or%uA0truncate(2) that file.%uA0
标签 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
F_SETLEASE |
Set or remove a file lease according to which of the following values is specified in the integer%uA0arg:
%uA0
|
||||||||
A process may hold only one type of lease on a file. | |||||||||
Leases may only be taken out on regular files. An unprivileged process may only take out a lease on a file whose UID matches the file system UID of the process. A process with the%uA0CAP_LEASEꃊpability may take out leases on arbitrary files. | |||||||||
F_GETLEASE | Indicates what type of lease we hold on the file referred to by%uA0fdby returning either%uA0F_RDLCK,%uA0F_WRLCK, or%uA0F_UNLCK,indicating, respectively, that the calling process holds a read, a write, or no lease on the file. (The third argument to%uA0fcntl() is omitted.) |
When a process (the "lease breaker") performs an%uA0open() or%uA0truncate() that conflicts with a lease established via%uA0F_SETLEASE, the system call is blocked by the kernel and the kernel notifies the lease holder by sending it a signal (SIGIO by default). The lease holder should respond to receipt of this signal by doing whatever cleanup is required in preparation for the file to be accessed by another process (e.g., flushing cached buffers) and then either remove or downgrade its lease. A lease is removed by performing anF_SETLEASE%uA0command specifying%uA0arg%uA0as%uA0F_UNLCK. If we currently hold a write lease on the file, and the lease breaker is opening the file for reading, then it is sufficient to downgrade the lease to a read lease. This is done by performing an%uA0F_SETLEASEcommand specifying%uA0arg%uA0as%uA0F_RDLCK.
If the lease holder fails to downgrade or remove the lease within the number of seconds specified in%uA0/proc/sys/fs/lease-break-time%uA0then the kernel forcibly removes or downgrades the lease holder’s lease.
Once the lease has been voluntarily or forcibly removed or downgraded, and assuming the lease breaker has not unblocked its system call, the kernel permits the lease breaker’s system call to proceed.
If the lease breaker’s blocked%uA0open() or%uA0truncate() is interrupted by a signal handler, then the system call fails with the error%uA0EINTR, but the other steps still occur as described above. If the lease breaker is killed by a signal while blocked in%uA0open() ortruncate(), then the other steps still occur as described above. If the lease breaker specifies the%uA0O_NONBLOCK%uA0flag when calling%uA0open(), then the call immediately fails with the error%uA0EWOULDBLOCK, but the other steps still occur as described above.
The default signal used to notify the lease holder is SIGIO, but this can be changed using the%uA0F_SETSIG%uA0command to%uA0fcntl(). If a%uA0F_SETSIG%uA0command is performed (even one specifying SIGIO), and the signal handler is established using SA_SIGINFO, then the handler will receive a%uA0siginfo_t%uA0structure as its second argument, and the%uA0si_fd%uA0field of this argument will hold the descriptor of the leased file that has been accessed by another process. (This is useful if the caller holds leases against multiple files).
文件和目录更改通知
标签 | 描述 | ||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
F_NOTIFY |
(Linux 2.4 onwards) Provide notification when the directory referred to by%uA0fd%uA0or any of the files that it contains is changed. The events to be notified are specified in%uA0arg, which is a bit mask specified by ORing together zero or more of the following bits:
%uA0
(In order to obtain these definitions, the _GNU_SOURCE feature test macro must be defined.) Directory notifications are normally "one-shot", and the application must re-register to receive further notifications. Alternatively, if%uA0DN_MULTISHOT%uA0is included in%uA0arg, then notification will remain in effect until explicitly removed.v A series of%uA0F_NOTIFY%uA0requests is cumulative, with the events inargꂾing added to the set already monitored. To disable notification of all events, make an%uA0F_NOTIFYꃊll specifying%uA0argas 0. Notification occurs via delivery of a signal. The default signal is SIGIO, but this can be changed using the%uA0F_SETSIG%uA0command to%uA0fcntl(). In the latter case, the signal handler receives asiginfo_t%uA0structure as its second argument (if the handler was established using SA_SIGINFO) and the%uA0si_fd%uA0field of this structure contains the file descriptor which generated the notification (useful when establishing notification on multiple directories). Especially when using%uA0DN_MULTISHOT, a real time signal should be used for notification, so that multiple notifications can be queued. NOTE:%uA0New applications should consider using the%uA0inotifyinterface (available since kernel 2.6.13), which provides a superior interface for obtaining notifications of file system events. See%uA0inotify(7). |
返回值
对于一个成功的调用,返回值取决于操作:
标签 | 描述 |
---|---|
F_DUPFD | The new descriptor. |
F_GETFD | Value of flags. |
F_GETFL | Value of flags. |
F_GETOWN | Value of descriptor owner. |
F_GETSIG | Value of signal sent when read or write becomes possible, or zero for traditional SIGIO behaviour. |
All other commands | |
%uA0 | Zero. |
On error, -1 is returned, and%uA0errno%uA0is set appropriately.
错误
标签 | 描述 |
---|---|
EACCES%uA0or%uA0EAGAIN | Operation is prohibited by locks held by other processes. |
EAGAIN | The operation is prohibited because the file has been memory-mapped by another process. |
EBADF | fd%uA0is not an open file descriptor, or the command was%uA0F_SETLKor%uA0F_SETLKW%uA0and the file descriptor open mode doesn’t match with the type of lock requested. |
EDEADLK | It was detected that the specified%uA0F_SETLKW%uA0command would cause a deadlock. |
EFAULT | lock%uA0is outside your accessible address space. |
EINTR | For%uA0F_SETLKW, the command was interrupted by a signal. ForF_GETLK%uA0and%uA0F_SETLK, the command was interrupted by a signal before the lock was checked or acquired. Most likely when locking a remote file (e.g. locking over NFS), but can sometimes happen locally. |
EINVAL | For%uA0F_DUPFD,%uA0arg%uA0is negative or is greater than the maximum allowable value. For%uA0F_SETSIG,%uA0arg%uA0is not an allowable signal number. |
EMFILE | For%uA0F_DUPFD, the process already has the maximum number of file descriptors open. |
ENOLCK | Too many segment locks open, lock table is full, or a remote locking protocol failed (e.g. locking over NFS). |
EPERM | Attempted to clear the%uA0O_APPEND%uA0flag on a file that has the append-only attribute set. |
注意
The errors returned by%uA0dup2() are different from those returned by%uA0F_DUPFD.
Since kernel 2.0, there is no interaction between the types of lock placed by%uA0flock(2) and%uA0fcntl(2).
POSIX.1-2001 allows%uA0l_len%uA0to be negative. (And if it is, the interval described by the lock covers bytes%uA0l_start+l_len%uA0up to and including%uA0l_start-1.) This is supported by Linux since Linux 2.4.21 and 2.5.49.
Several systems have more fields in%uA0struct flock%uA0such as e.g.%uA0l_sysid. Clearly,%uA0l_pid%uA0alone is not going to be very useful if the process holding the lock may live on a different machine.
BUGS
A limitation of the Linux system call conventions on some architectures (notably x86) means that if a (negative) process group ID to be returned by%uA0F_GETOWNꃺlls in the range -1 to -4095, then the return value is wrongly interpreted by glibc as an error in the system call that is, the return value of%uA0fcntl() will be -1, and%uA0errno%uA0will contain the (positive) process group ID.
In Linux 2.4 and earlier, there is bug that can occur when an unprivileged process usesF_SETOWN%uA0to specify the owner of a socket file descriptor as a process (group) other than the caller. In this case,%uA0fcntl() can return -1 with%uA0errno%uA0set to%uA0EPERM, even when the owner process (group) is one that the caller has permission to send signals to. Despite this error return, the file descriptor owner is set, and signals will be sent to the owner.
遵循于
SVr4, 4.3BSD, POSIX.1-2001. Only the operations F_DUPFD, F_GETFD, F_SETFD, F_GETFL, F_SETFL, F_GETLK, F_SETLK, F_SETLKW, F_GETOWN, and F_SETOWN are specified in POSIX.1-2001.
F_GETSIG, F_SETSIG, F_NOTIFY, F_GETLEASE, and F_SETLEASE are Linux specific. (Define the _GNU_SOURCE macro to obtain these definitions.)