linux flock使用示例代码

来源:互联网 发布:linux常考面试题 编辑:程序博客网 时间:2024/06/05 20:18

代码如下:

#include <stdlib.h>

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>

int main(int args, char** argv)
{
int n1 = atoi(argv[1]);
int n2 = atoi(argv[2]);
int n3 = atoi(argv[3]);
printf("%d  %d lock %d - %d \n", args, n1, n2, n3);

printf("pid [%d] \n", getpid());

int fd = open("1.log", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
if(fd == -1)
        printf("open error %d", errno);
struct flock flk;
flk.l_type = n1 == 1 ? F_WRLCK : F_RDLCK;
flk.l_whence = SEEK_SET;
flk.l_start = n2;
flk.l_len = n3;
int nRet = fcntl(fd, F_SETLK, &flk);
printf("fcntl lock ret:%d \n", nRet);
if(nRet == -1)
{
flk.l_type = F_RDLCK;
flk.l_whence = SEEK_SET;
flk.l_start = n2;
flk.l_len = n3;
nRet = fcntl(fd, F_GETLK, &flk);
printf("type F_WRLCK[%d] F_RDLCK[%d] F_UNLCK[%d]\n", F_WRLCK, F_RDLCK, F_UNLCK);
printf("whence SEEK_SET[%d] SEEK_CUR[%d] SEEK_END[%d] \n", SEEK_SET, SEEK_CUR , SEEK_END);
printf("ret[%d]    current lock pid[%d] type[%d] whence[%d] start[%d] len[%d] \n", nRet, flk.l_pid, flk.l_type, flk.l_whence, flk.l_start, flk.l_len);

struct stat buf;
nRet = stat("1.log", &buf);
printf("stat ret:%d   fileSize:%d \n", nRet, buf.st_size);
}
sleep(10);
return 0;
}



3个参数, 参数1:1 是写锁,0是读锁; 参数2:起始字节索引;参数3:待锁字节长度

./a.out 1 0 10

./a.out 0 2 4


如果锁失败,会获取当前锁的信息并打印;

如果锁了10字节, 解锁中间的一个字节,会被分割变成2个锁


详见 unix环境高级编程14.2节

0 0
原创粉丝点击