📄 lock.c
字号:
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void lock_set(int fd,int type);
int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len);
int main(int argc, char *argv[])
{
int fd,nwrite,nread,len, c;
char reply;
char buff[100];
char buf_r[100];
/*打开文件*/
fd=open("hello",O_RDWR | O_CREAT, 0666);
if(fd < 0){
perror("open");
exit(1);
}
/*使用getopt函数获取客户端选项*/
while ((c = getopt(argc, argv, "w:r")) != -1)
switch(c)
{
/*加上写入锁*/
case 'w':
strcpy(buff, optarg);
lock_set(fd, F_WRLCK);
len = sizeof(buff);
if((nwrite=write(fd,buff,len))>0){
printf("write success\n");
}
while(1)
{
printf("want to unlock?(Y/N)\n");
scanf("%c",&reply);
/*给文件上锁*/
if((reply == 'Y') || (reply == 'y'))
{
lock_set(fd, F_UNLCK);
break;
}
else
{
sleep(2);
continue;
}
}
break;
/*加入读取锁*/
case 'r':
lock_set(fd, F_RDLCK);
lseek(fd,0,SEEK_SET);
if((nread=read(fd,buf_r,100)) > 0){
printf("read:%s\n",buf_r);
}
while(1)
{
printf("want to unlock?(Y/N)\n");
scanf("%c",&reply);
/*给文件上锁*/
if((reply == 'Y') || (reply == 'y'))
{
lock_set(fd, F_UNLCK);
break;
}
else
{
sleep(2);
continue;
}
}
break;
default:
printf("prog [-w+content] [-r]\n");
break;
}
close(fd);
exit(0);
}
/*测试锁例子*/
lock_test(int fd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type; /*可以为F_RDLCK或者F_WRLCK*/
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
if(fcntl(fd, F_GETLK, &lock) < 0)
perror("fcntl");
if(lock.l_type == F_UNLCK)
return(0);
return(lock.l_pid);
}
/*给文件加锁解锁例子*/
int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type; /*F_RDLCK, F_WRICK, F_UNLCK*/
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
return(fcntl(fd, cmd, &lock))
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -