Go Linux system call--fcntl function

Source: Internet
Author: User
Tags flock flock lock

Function Description: Manipulate file characteristics According to the file description.

File Control function Fcntl
Header file:

#include <unistd.h>

#include <fcntl.h>

Function Prototypes:

int fcntl (int fd, int cmd);

int fcntl (int fd, int cmd, long arg);

int fcntl (int fd, int cmd, struct flock *lock);

Describe:

FCNTL () provides control over (file) descriptors. The parameter FD is a descriptor of the parameter CMD operation (as described below).

For CMD values, Fcntl can accept the third parameter (ARG)

There are 5 functions of the FCNTL function:

1. Copy an existing descriptor (CMD=F_DUPFD).

2. Get/Set the file descriptor tag (CMD=F_GETFD or F_SETFD).

3. Get/Set the 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,F_SETLK or F_SETLKW).

CMD option:

F_DUPFD returns a (file) descriptor as described below:

(1) A minimum of one of the available descriptors greater than or equal to ARG

(2) A reference to an object like the original operator

(3) If the object is a file, a new descriptor is returned, and the descriptor shares the same offset as the ARG (offset)

(4) Same access mode (read, write or read/write)

(5) Same file status flag (for example: Two file descriptors share the same status flag)

(6) The CLOSE-ON-EXEC flag that is combined with the new file descriptor is set to the system call of the cross-access Execve (2)

F_GETFD obtains a joint close-on-exec flag with the file descriptor FD, similar to fd_cloexec. If the return value and Fd_cloexec are performed with the result of the operation being 0, the file remains interleaved to access exec (), Otherwise, the file will be closed (ARG is ignored) if it is run by exec

F_SETFD set close-on-exec flag. The flag is determined by the fd_cloexec bit of the parameter arg.

F_GETFL gets the file status flag of FD as described below (ARG is ignored)

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.
F_getown Gets the process ID or process group ID that is currently receiving the Sigio or Sigurg signal, and the process group ID is returned as a negative value (ARG is ignored)

F_setown settings will receive the process ID or process group ID of the Sigio and Sigurg signals, the process group ID is indicated by providing a negative value of ARG, otherwise, ARG will be considered a process ID

The command Word (cmd) F_GETFL and F_SETFL flags 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 returns-1 and Eagain error O_appe ND 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

Note: You must be careful when modifying the file descriptor flag or file status flag to get the current flag value, then modify it as desired, and then set the new flag value. You cannot just execute the F_SETFD or F_SETFL command, which turns off the previously set flag bit.

The return value of the FCNTL: 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,F_GETFD,F_GETFL and F_getown. The first returns a new file descriptor, the second returns the corresponding flag, and the last one returns a positive process ID or a negative process group ID.

One: The first kind is similar to the DUP operation, which does not make an example here. (FCNLT (OLDFD, F_DUPFD, 0) <==>dup2 (OLDFD, NEWFD))

Set up

Create a child process in this function, call execl

 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 int main () 6 {7 pid_t pid; 8 Open the file as an append 9 int fd = FD = open ("Test.txt", O_trunc | O_rdwr | O_append | O_creat, 0777); (FD < 0) Each {perror ("open"); return-1;14}15 printf ("FD =%d\n ", FD); Fcntl (FD, F_SETFD, 0);//Close the close-on-exec sign of FD (FD," Hello C program\n ", strlen (" Hello C (program!\n ")); pid = fork (), if (PID < 0) @ (" fork "), Perror return-1;2 6}27 if (PID = = 0) ("FD =%d\n", fd); int ret = EXECL ("./main", "./ma          In ", (char *) &AMP;FD, NULL), if (Ret < 0) perror (" Execl "); exit (-1); 36 }37 exit (0);}39-Wait (NULL); write (fd, "Hello C + + program!\n", strlen ("Hello C + + PR Ogram!\n ")); close (FD); return 0;47}

Main test function

1 int main (int argc, char *argv[]) 2 {3     int fd = (int) (*argv[1]);//Descriptor 4      5     printf ("FD =%d\n", FD); 6  7
   int ret = write (fd, "Hello linux\n", strlen ("Hello linux\n")); 8     if (Ret < 0) 9     {         perror ("write");         return-1;12     }13     Close (FD);     0;17}

Post-execution file results:

[email protected] class_2]# cat Test.txt
Hello C Program
Hello Linux
Hello C + + program!

Three: Set file flags with command F_GETFL and F_SETFL, such as blocking and non-blocking

 1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <unistd.h> 4 #include <sys/stat.h> 5 #in Clude <fcntl.h> 6 #include <string.h> 7 8/********************** enable non-blocking i/o******************** 9 *int flags;1 0 *if (flags = FCNTL (FD, F_GETFL, 0) < 0) *{12 * perror ("fcntl"); return-1;14 *}15 *flags |= o_nonblock;16 *if (Fcntl (FD, F_SETFL, Flags) < 0) *{18 * perror ("fcntl"); return-1;20 *}21 ****************************** /22 23/********************** off non-blocking i/o******************24 flags &= ~o_nonblock;25 if ( Fcntl (FD, F_SETFL, Flags) < 0) (perror ("Fcntl"), return-1;29}30 **************************************     /31 int main () {buf[10 char] = {0};35 int ret;36 int FLAGS;37 38//Use non-blocking io39     if (flags = Fcntl (Stdin_fileno, F_GETFL, 0) < 0) @ + perror ("Fcntl"); return-1;43}44 Flags |= O_NONBLOCK;45 If(Fcntl (Stdin_fileno, F_SETFL, Flags) < 0) (perror ("Fcntl"); return-1;49}50             E (1) (2); Stdin_fileno ret = read (+/-9); BUF (ret = = 0) 56 {57         Perror ("Read--no"),}59 Else60 {the "read =%d\n", ret); 62}63 * Write (Stdout_fileno, buf, Ten), memset (buf, 0, ten);

Four: Setting up asynchronous IO is not ready to be realized later (oh ... )

Five: Set get record lock

Pointer to struct flock:

struct FLCOK

{

short int l_type; /* Locked Status */

These three parameters for the segmentation of the file lock, if the entire file lock, then: l_whence=seek_set,l_start=0,l_len=0;

Short int l_whence;/* determines l_start position */

off_t L_start; /* Start position of locked area */

off_t L_len; /* Size of locked area */

pid_t L_pid; /* Process for locking actions */

};

There are three states of L_type:

F_rdlck creating a lock for reading

F_wrlck creating a lock for write-in

F_unlck Delete a previously established lock

There are three ways of L_whence:

Seek_set begins with the start of the file as the starting position of the lock.

Seek_cur starting position with the current file read and write location as locked

Seek_end the starting position of the lock with the end of the file.

 1 #include "filelock.h" 2 3/* Set a read lock */4 int readlock (int fd, short start, short whence, short Len) 5 {6 struct Flock lock; 7 Lock.l_type = F_rdlck; 8 Lock.l_start = start; 9 Lock.l_whence = whence;//seek_cur,seek_set,seek_end10 Lock.l_len = len;11 lock.l_pid = Getpid (); 12//block mode Plus Lock if (Fcntl (FD, f_setlkw, &lock) = = 0) return 1;15 return 0;17}18 19/* Set a read lock, do not wait for */20 I     NT READLOCKNW (int fd, short start, short whence, short len) {in struct flock lock;23 Lock.l_type = f_rdlck;24 Lock.l_start = start;25 Lock.l_whence = whence;//seek_cur,seek_set,seek_end26 Lock.l_len = len;27 lock.l_pi D = getpid (); 28//non-blocking mode plus lock if (fcntl (FD, F_SETLK, &lock) = = 0) return 1;31 0;33}34  /* Set a write lock */35 int writelock (int fd, short start, short whence, short Len), (PNS) flock lock;38 Lock.l_type = f_wrlck;39 Lock.l_start = start;40 lock.l_whence = whence;41 LOck.l_len = len;42 Lock.l_pid = Getpid (); 43 44//Blocking mode plus lock if (fcntl (FD, f_setlkw, &lock) = = 0) Turn 1;47 return 0;49}50 51/* Set a write lock */52 int writelocknw (int fd, short start, short whence, short Len) 53 {5 4 struct flock lock;55 Lock.l_type = f_wrlck;56 Lock.l_start = start;57 lock.l_whence = whence;58 Lock . L_len = len;59 lock.l_pid = Getpid (); 60 61//non-blocking mode locking if (Fcntl (FD, F_SETLK, &lock) = = 0) + retur  N 1;64 return 0;66}67 68/* Unlock */69 int unlock (int fd, short start, short whence, short Len) Flock lock;72 Lock.l_type = f_unlck;73 Lock.l_start = start;74 lock.l_whence = whence;75 Lock.l_len = Len  ; lock.l_pid = Getpid (); if (Fcntl (FD, f_setlkw, &lock) = = 0) return 1;80 bayi return 0;82}

Go Linux system call--fcntl function

Related Article

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.