Linux fcntl functions

Source: Internet
Author: User
Tags flock

Fcntl
Function Description: Manipulate the attributes of the file according to the file description.
#include <unistd.h>
#include <fctl.h>
int fcntl (int fd, int cmd);
int fcntl (int fd, int cmd, long arg);
int fcntl (int fd, int cmd, struct flock *lock);

http://blog.csdn.net/xiaoliangsky/article/details/40303245

Describe
FCTL provides control for (file) descriptions. FD is a descriptor of the parameter CMD operation (as described below), Fctl can accept the third argument arg for the value of CMD.
return value
The return value of Fctl () is related to the command. If there is an error, all commands return-1, and if successful, some other value is returned. The following three commands have a specific return value:
F_DUPFD returns a new file descriptor
F_GETFD return the corresponding flag
F_GETFL returning a file status token
F_getown returns a positive process ID or a negative process group ID

The FCNTL function has 5 functions:
1) Copy an existing descriptor (CM=F_DUPFD)
2) Get/Set File descriptor tag (CMD=F_GETFD or F_SETFD)
3) Get/Set file status tag (CMD=F_GETFL or F_SETFL)
4) Get/Set asynchronous I/O ownership ((Cmd=f_getown or F_setown)
5) Get/Set record lock (CMD=F_GETLK or F_set)

1. CMD=F_DUPFD
F_DUPFD returns a (file) descriptor as described below
• A minimum of one of the available descriptors greater than or equal to ARG
• Reference to an object like the original operator
• If the object is a file, a new descriptor is returned that shares the same offset as ARG (offset)
• Same access mode (read, write or read/write)
• Same file status flag (e.g.: Two file descriptors share the same status flag)
• The CLOSE-ON-EXEC flag that is combined with the new file descriptor is set as a system call for cross-access Execve (2)
Actually invoke the DUP (OLDFD);
is equivalent to
Fcntl (ODLFD, F_DUPFD, 0);
and call Dup2 (OLDFD, NEWFD);
is equivalent to
Close (OLDFD);
Fcntl (OLDFD, F_DUPFD, NEWFD);

2. Cmd=f_getfd or F_SETFD
F_GETFD obtains the CLOSE-ON-EXEC flag associated with the file descriptor FD, similar to fd_cloexec. If the return value and Fd_cloexec are performed with the result of the operation, the file remains interleaved with exec (), otherwise the file will be closed (ARG is ignored) if run through exec
F_SETFD sets the CLOSE-ON-EXEC flag, which is determined by the fd_cloexec bit of the parameter arg, and it should be understood that many of the existing programs involving file descriptor flags do not use constant fd_cloexec, but instead set this flag to 0 (system default, Do not close at exec) or 1 (off at exec)
Caution must be taken when modifying the file descriptor flag or file status flag to obtain the current flag value, then modify it as desired, and finally set the new flag value. You cannot just execute the F_SETFD or F_SETFL command, which turns off the previously set flag bit.

3. F_GETFL and F_SETFL of the CMD value:
F_GETFL obtains the file status flag of FD, as described below (ARG is ignored), when describing the open function, the file status flag is indicated. Unfortunately, three access-mode flags (O_rdonly, o_wronly, and O_RDWR) do not account for 1. (The values of these three flags are 0, 1, and 2, for historical reasons, these three values are mutually exclusive-one file can only have one of these three values) so first you have to use the masked character o_accmode and the access-mode bit, and then compare the result to these three values.
F_SETFL set to the ARG descriptor status flag, several flags that can be changed are: O_append,o_nonblock,o_sync and O_async. There are 7 file status flags in Fcntl: O_rdonly, O_wronly, O_rdwr, O_append, O_nonblock, O_sync and O_async.

Several flags that can be changed are described below:
O_nonblock non-blocking I/O if the Read (2) call does not have readable data, or if the write (2) operation is blocked, the read or write call will return 1 and Eagain error
O_append force each write operation to be added at the end of the file, equivalent to the O_APPEND flag of open (2)
O_direct minimizes or removes the cache impact of reading and writing. The system will attempt to avoid caching your read or write data. If it is not possible to avoid caching, it will minimize the impact of data that has already been cached. If the logo is not good enough, it will greatly reduce the performance
O_async allows the Sigio signal to be sent to the process group when I/O is available, for example: when there is data to read

4. Cmd=f_getown and F_getown
F_getown Gets the process ID or process group ID that is currently accepting the Sigio or Siurg signal, and the process group ID returns a negative value (ARG is ignored)
The F_setown setting will accept the process ID or process group ID of the Sigio or Sigurg signal, and the process group ID is described by providing a negative value of ARG (a process group ID for the absolute value of arg), otherwise ARG will be considered a process ID

5. Cmd=f_getlk,f_setlk or F_SETLKW
Get/Set the function of record lock, successful return 0, if have error return 1, error reason exists in errno.
F_GETLK obtains the first blocking lock description point by using the third parameter, ARG (a struct that points to flock). The information obtained will overwrite the information of the flock structure uploaded to Fctl (). If no locks are found to prevent this lock from being generated, the structure will not be changed unless the type of the lock is set to F_unlck
F_SETLK Sets or clears the segment lock of a file according to the information about the lock described by the third argument to the pointer to struct flock, Arg. F_SETLK is used to implement shared (or read) locks (F_RDLCK) or exclusive (write) locks (f_wrlck), which can also be removed from both locks (f_unlck). If a shared or exclusive lock cannot be set, Fcntl () will return immediately eagain
F_SETLKW This command is the same as F_SETLK except for shared or exclusive locks that are blocked by other locks. If a shared or exclusive lock is blocked by another lock, the process waits until the request can be completed. When Fcntl () is waiting for an area of the file to capture a signal, if the signal is not specified Sa_restart,fcntl will be interrupted

When a shared lock is set to a segment of a file, other processes can set a shared lock to this segment or part of the segment. A shared lock prevents any other process set from being exclusively locked into any part of this protected area. If the file descriptor is not opened with read access, the set request for the shared lock fails.
An exclusive lock prevents any other process from setting a shared or exclusive lock anywhere in this protected area. If the file descriptor is not opened in writing, the exclusive lock request fails.

Pointer to struct flock:

struct flock{short    int l_type;//locked state short    int l_whence;//determines l_start position    off_t     l_start;//The start position of the locked area    off_t     l_len;//the size of the locked area    pid_t     l_pid;//The process of locking the action};

There are three states of L_type:
F_rdlck creating a lock for reading
F_wrlck creating a lock for writing
F_unlck Delete a previously established lock

There are three ways of L_whence:
Seek_set starting position of the lock with the beginning of the file
Seek_cur start position with end of file as lock
Seek_end start position with end of file as lock

Fcntl There are two types of locks: recommended and mandatory locks
The recommended lock is this: each process that uses a locked file checks to see if there is a lock and, of course, respects the existing lock. The kernel and the tether generally insist on not using the proposed lock, which relies on the programmer to comply with this rule.
A mandatory lock is used by the kernel: When a file is locked for write operations, the kernel blocks any read-write access to the file before the process that locks it, and each read or write access checks to see if the lock exists.
System default Fcntl are recommended locks, mandatory locks are non-POSIX standard. If you want to use a mandatory lock, to make the entire system can use a mandatory lock, you need to re-mount the file system, mount using the parameters-0 mand to open a mandatory lock, or close the locked file group execution permissions and open the file's set-gid permission bit.
Recommended locks are only used between cooperating processes. The understanding of the cooperating process is most important, referring to processes that affect other processes or processes that are affected by other processes, with two examples:
1) We can run the same command in two windows simultaneously and operate on the same file, then these two processes are cooperating processes
2) Cat File | Sort, then the process that the cat and sort produces is the cooperating that uses the pipe processes

I/O operations using the Fcntl file lock must be careful: how the process handles the lock before starting any I/O operations, and how to do all of the operations before unlocking the file must be considered. If the file is opened before the lock is set, or if the file is closed after the lock is read, another process may access the file within a fraction of a second between the lock/unlock operation and the on/off operation. When a process locks a file, regardless of whether it releases the added lock, as long as the file is closed, the kernel automatically releases the proposed lock on the file (which is also the biggest difference between the proposed and mandatory locks), so do not want to set up a proposed lock to achieve the purpose of permanently not allowing other processes to access the file (mandatory lock) ; A mandatory lock works for all processes.

Fcntl uses three parameters F_setlk/f_setlkw,f_unlck and f_getlk to separately request, release, and test the record locks. Record locks is a lock on a file rather than an entire file, and this meticulous control allows the process to collaborate better to share files. Fcntl can be used to read and write locks, and read lock is also called shared lock, because multiple cooperating processes can establish a read lock on the unified part of the file; write lock is called Excluseive lock ( Repel locks), because at any moment there can only be one cooperating processes in a part of the file to establish a write lock. If cooperating processes the file, they can add read lock to the file at the same time, and the other cooperating must be released before a cooperating processes plus write lock Processes loads the file's read lock and write lock, which means that only one write lock exists for the file, and read lock and write lock cannot coexist.

The following example uses F_GETFL to get the file status information:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include < Fcntl.h>int Main () {int   fd;int   var;if (fd = open ("Test.txt", O_RDWR | O_creat | O_EXCL, 0664)) = =-1) {perror ("open error"); exit (1);} if (var = fcntl (fd, F_GETFL, 0)) < 0) {perror ("Fcntl error"), close (FD); exit (1);} Switch (var & o_accmode) {case o_rdonly:printf ("Read only. \ n "); Break;case o_wronly:printf (" Write only. \ n "); Break;case o_rdwr:printf (" Read and Write: \ n "); break;default:printf (" Do ' t know. \ n "); if (Var & o_append) {printf ("and APPEND. \ n ");} if (Var & o_nonblock) {printf ("and nonblocking. \ n ");} if (Close (FD) = =-1) {perror ("close Error");} return 0;}

Example of a test lock

http://blog.csdn.net/xiaoliangsky/article/details/40303245

Read Plus write lock in the same process test

#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <      Fcntl.h>int Main () {int fd;int fret;struct flock rdflk;struct flock wrflk;struct flock tmflk;///* about locking: 1) If the file is read-only, read-only, and the write-lock fails to return-12) If the file is open with write-only, only write-lock, read-lock will fail to return-13) If the file is read-write open, in the same process, if two locks are added at the same time,   The post-add lock overrides the previous lock. For example, the first to write a lock, after the read lock, the results of the file plus a read lock, if the first read the lock, after the write lock, the file is finally added to the write lock. *if (fd = open ("Test.txt", o_rdwr) = =-1) {perror ("open error"); exit (1);} if (fret = Fcntl (FD, f_getfd) = = =-1) {perror ("Fcntl error"); exit (1);} Fcntl (FD, F_SETFD, 1);//when exec is off rdflk.l_type = F_rdlck;rdflk.l_whence = Seek_set;rdflk.l_start = 0;rdflk.l_len = 100  Wrflk = Rdflk;wrflk.l_type = f_wrlck;//file First read lock if (Fcntl (FD, F_SETLK, &rdflk) = =-1) {perror ("Fcntl set Rdflk Error "); exit (1);} After the write lock, the final write lock will overwrite the read lock, the file Plus is the write lock if (Fcntl (FD, F_SETLK, &wrflk) = = 1) {perror ("Fcntl set wrflk error"); exit (1);}                //In this fcntl (FD, F_geTLK, &tmflk);        return 0;} 

Read-only open, add write lock error

#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include < Fcntl.h>int Main () {int              fd;int              fret;struct flock     rdflk;struct flock     wrflk;//about locking:// 1) If the file is read-only, read-only, the lock will fail to return -1if (FD = open ("Test.txt", o_rdonly) = =-1) {perror ("open error"); exit (1);} Rdflk.l_type   = f_rdlck;rdflk.l_whence = Seek_set;rdflk.l_start  = 0;rdflk.l_len    = 100;wrflk          = rdflk; Wrflk.l_type   = f_wrlck;//Write lock, an error occurs because the file is a read-only open//fcntl set wrflk Error:bad file Descriptorif (fcntl (FD, F_SETLK, & AMP;WRFLK) = =-1) {perror ("Fcntl set wrflk error"); exit (1);} return 0;}
Also error opening read-only lock with write-only:

2) If the file is open with write-only, only the write lock, the read lock will fail to return -1if ((fd = open ("Test.txt", o_wronly) = =-1) {perror ("open error"); exit (1);} Read lock, error occurs because the file is opened with write-only//fcntl set wrflk Error:bad file Descriptorif (fcntl (FD, F_SETLK, &rdflk) = =-1) {perror ("fcnt L Set wrflk error "); exit (1);}

Open in read-write mode, lock between different processes
/*
When a shared lock is set to a segment of a file, other processes can set a shared lock to this segment or part of the segment. A shared lock prevents any other process set from being exclusively locked into any part of this protected area. If the file descriptor is not opened with read access, the set request for the shared lock fails.
An exclusive lock prevents any other process from setting a shared or exclusive lock anywhere in this protected area. If the file descriptor is not opened in writing, the exclusive lock request fails.
Summary: If there is a process write lock, the other process cannot add any locks, and if it is a read lock, the other process can only read the lock.
*/

Code:

#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <              fcntl.h> #include <sys/types.h> #define Buf_size 512int Main () {int Fd;int bytes_read;int status;pid_t pid;const char *chbuf;char buf[buf_size];struct flock Tmflk;stru CT flock rdflk;struct flock wrflk;chbuf = "xxxxx"; rdflk.l_type = F_rdlck;rdflk.l_whence = SEEK_SET;RDFL K.l_start = 0;rdflk.l_len = 100;wrflk = Rdflk;tmflk = Rdflk;wrflk.l_type = f_wrlck;//open between processes in read-write mode, Read and write locks between different processes (FD = open ("Test.txt", O_RDWR | o_append)) = =-1) {perror ("open error"); exit (1);} if (PID = fork ()) < 0) {perror ("fork Error"); exit (1);}    else if (PID > 0) {//parent process plus read lock if (Fcntl (FD, F_SETLK, &wrflk) = =-1) {perror ("Parent fcntl set RDFLK error"); exit (1); }//the process attempts to lock sleep (1);//write Data if (write (fd, chbuf, sizeof (chbuf)) = = 1) {perror ("Parent write Error");} Tmflk = RDFLK;TMFLk.l_type = f_unlck;//The child process attempts to request a lock so that the test can not lock sleep (3) in the case of a read lock, or the release lock if (Fcntl (FD, F_SETLK, &tmflk) = =-1) {perror (" Fcntl unlck error ");} Waitpid (PID, &status, 0);//wait for the child process to return}else{sleep (1); tmflk = rdflk;//try to yoke while (1) {//Get file lock information if (Fcntl (FD, F_GETLK, &A MP;TMFLK) = =-1) {perror ("Child fcntl getlk Error");} if (Tmflk.l_type = = F_unlck) {break;} if (Tmflk.l_type = = F_rdlck) {printf ("process id:%d have locked with f_rdlck\n", tmflk.l_pid);} else if (Tmflk.l_type = = F_wrlck) {printf ("process id:%d have locked with f_wrlck\n", tmflk.l_pid);} Sleep (1);} Read lock if (Fcntl (FD, F_SETLK, &rdflk) = =-1) {perror ("Fcntl setlk rdflk Error"); exit (1);} printf ("Child fcntl Get the rdflk\n"); Lseek (FD, Rdflk.l_whence, Rdflk.l_start);//reposition if (Bytes_read = Read (FD, buf, buf_ SIZE) < 0) {perror ("read error"); exit (1);} Buf[bytes_read-1] = ' + '; write (Stdout_fileno, buf, Bytes_read);p rintf ("\ n"); tmflk = Rdflk;tmflk.l_type = F_UNLCK;FC NTL (FD, F_SETLK, &tmflk);} Close (FD); return 0;}



Here's a blog post: http://blog.sina.com.cn/s/blog_4b226b9201011974.html is also good at writing.
Parameters:
FD: File description Word.
CMD: Operation command.
ARG: The parameter to use for the command.
Lock: Ibid.

The following commands are available for use
One. F_DUPFD: Copy the file description Word.
Two. Fd_cloexec: Set the CLOSE-ON-EXEC flag. If the fd_cloexec bit is 0, the file remains open during Execve execution. Otherwise, it is closed.
Three. F_GETFD: Read the file description Word flag.
Four. F_SETFD: Sets the file description Word flag.
Five. F_GETFL: Read the file status flag.
Six. F_SETFL: Sets the file status flag.
Among them o_rdonly, O_wronly, O_rdwr, O_creat, O_excl, O_noctty and O_trunc were unaffected,
Flags that can be changed are O_append,o_async, O_direct, O_noatime, and O_nonblock.
Seven. F_getlk, F_setlk, and f_setlkw: Gets, releases, or tests the record lock, the parameter used is the following struct-body pointer:
F_SETLK: Gets the Lock (F_rdlck, F_WRLCK) or Release lock (F_UNLCK) in the specified byte range. If there is a conflict with another process's lock operation, return 1 and set errno to Eacces or Eagain.

F_SETLKW: Behaves like a f_setlk, except that sleep waits when a lock cannot be acquired. If the signal is received during the wait, the errno is returned immediately and the EINTR is placed.
F_GETLK: Gets the file lock information.
F_unlck: Release the file lock.

In order to set a read lock, the file must be opened in read mode. In order to set a write lock, the file must be opened in write mode. In order to set a read-write lock, the file must be opened in read/write mode.

Eight. Signal management
F_getown, F_setown, F_getsig, and F_setsig are used for IO-acquired signals.
F_getown: Gets the process or process group ID that is currently receiving the Sigio or Sigurg event signal on the file descriptor FD.
F_setown: Sets the process or process group ID that will receive the Sigio or Sigurg event signal on the file descriptor FD.
F_getsig: Gets the signal that identifies the input and output to be made.
F_setsig: Sets the signal that can be used to identify the input and output.

With the above command, most of the time the program does not need to use Select () or poll () to achieve full asynchronous I/O.

Nine. Lease (leases)
F_setlease and f_getlease are used for leases on files of the current process. A file lease provides a mechanism by which a process that owns a file lease will be notified when a process attempts to open or break a file's contents.

F_setlease: Set or delete file leases based on the following symbol values

1.F_RDLCK sets the read lease, and the current process that owns the lease is advertised when the file is opened or broken by another process in writing.
2.f_wrlck sets a write lease, and the current process that owns the lease is advertised when the file is opened or broken by another process, either read or write.
3.f_unlck Delete a file lease.

F_getlease: Gets the lease type.

10. File or directory change notice
(Linux 2.4 or more) when a file in the directory or directory containing the FD index changes, a notification is issued to the process. The arg parameter specifies that the advertised event has the following, and that two or more values can be combined by a or operation.
1.dn_access files are accessed (read, pread, READV)
2.dn_modify file was modified (write, Pwrite,writev, truncate, ftruncate)
3.dn_create file was created (open, creat, Mknod, mkdir, link, symlink, rename)
4.dn_delete file was deleted (unlink, RmDir)
5.dn_rename file is renamed (RENAME)
6.dn_attrib file attributes changed (Chown, chmod, Utime[s])

Return Description:
When executed successfully, there are different return values for different operations
F_DUPFD: New File Description Word
F_GETFD: Flag Value
F_GETFL: Flag Value
F_getown: Document description Word belongs to master
F_GETSIG: Notification signal to be sent when read and write becomes feasible, or 0 for traditional Sigio behavior

Returns 0 for other commands.

The failed return -1,errno is set to one of the following values
Eacces/eagain: Operation not allowed, not yet feasible
EBADF: Invalid file description
Edeadlk: Detection of a deadlock may occur
Efault: Lock operation occurs outside the accessible address space
EINTR: Operation interrupted by signal
EINVAL: Invalid Parameter
Emfile: The process has exceeded the maximum available range of files
Enolck: The lock has been exhausted
Eperm: Power not allowed

See information:

Http://www.cnblogs.com/andtt/articles/2178875.html


Linux fcntl functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.