fcntl函数用法——设置文件锁

fcntl函数。锁定文件,设置文件锁。
设置获取文件锁:F_GETLK 、F_SETLK  、F_SETLKW
文件锁结构,设置好用于fcntl函数的第三个参数。
struct flock
{
    short    l_type;//锁的类型 F_RDLCK,F_WRLCK(排他锁),F_UNLCK(清除锁)
    short    l_whence;//锁的范围 SEEK_SET, SEEK_CUR, SEEK_END 文件开头,当前位置,结尾。基准位置
    off_t  l_start;//相对于基准的偏移值。定义了锁的起始
    off_t  l_len;//锁的字节数
    pid_t    l_pid;//获取哪个进程处于阻塞。仅仅当(set by F_GETLK and F_OFD_GETLK)
};

 1 #include<unistd.h>
 2 #include<sys/types.h>
 3 #include<sys/stat.h>
 4 #include<fcntl.h>
 5 #include<stdlib.h>
 6 #include<stdio.h>
 7 #include<errno.h>
 8 #include<string.h>
 9 #define ERR_EXIT(m)
10     do
11     {
12         perror(m);
13         exit(EXIT_FAILURE);
14     }while(0)  //宏要求一条语句
15 int main(int argc,char*argv[])
16 {
17     int fd;
18     fd=open("test2.txt",O_CREAT|O_RDWR|O_TRUNC,0644);
19     if(fd==-1)
20         ERR_EXIT("open error");
21     struct flock lock;
22     memset(&lock,0,sizeof(lock));
23     lock.l_type=F_WRLCK;//排它锁
24     lock.l_whence=SEEK_SET;
25     lock.l_start=0;
26     lock.l_len=0;//=0表示锁定整个文件。
27 
28     //if(fcntl(fd,F_SETLK,&lock)==0)
29     //F_SETLK,如果锁已经被一个进程加锁,则另一个进程再施加锁会返回失败。F_SETLKW的话,则另一个进程施加锁会阻塞。
30     if(fcntl(fd,F_SETLKW,&lock)==0) //另一个进程再次运行该程序加锁时会阻塞,直到一进程释放
31     {
32 
33         printf("lock success
");
34         printf("please press any key to unlock
");//再开一个进程运行程序加锁会失败。
35         getchar();//读取任何字符。
36         lock.l_type=F_UNLCK;
37         if(fcntl(fd,F_SETLK,&lock)==0)
38             printf("unlock success
");
39         else
40             ERR_EXIT("unlock fail");
41     }
42     else
43         ERR_EXIT("lock fail");
44     return 0;
45 }
原文地址:https://www.cnblogs.com/wsw-seu/p/8289821.html