📄 prg9_1.c
字号:
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#define SEQFILE "zjm.txt"
#define MAXLINE 256
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int lock_reg(int fd,int cmd,int type,off_t offset,int whence,off_t len);
pid_t lock_test(int fd, int type,off_t offset,int whence, off_t len);
/**brief 锁操作参数宏参数
* 如果len=0 表示整个文件
* \param fd -- 进程ID
* \param type -- 命令类型F_RDLCK,F_WRLCK,F_UNLCK
* \param offset -- 记录偏移量,即上锁记录的开始位置,byte offset,relative to l_whence
* \param whence -- 是以下之中的一个:SEEK_SET,SEEK_CUR,SEEK_END
* \param len -- 记录的长度
*/
///返回-1--错误
#define read_lock(fd,offset,whence,len) \
lock_reg(fd,F_SETLK,F_RDLCK,offset,whence,len)
///返回-1--错误
#define readw_lock(fd,offset,whence,len) \
lock_reg(fd,F_SETLKW,F_RDLCK,offset,whence,len)
///返回-1--错误
#define write_lock(fd,offset,whence,len) \
lock_reg(fd,F_SETLK,F_WRLCK,offset,whence,len)
///返回-1--错误
#define writew_lock(fd,offset,whence,len) \
lock_reg(fd,F_SETLKW,F_WRLCK,offset,whence,len)
///返回-1--错误
#define un_lock(fd,offset,whence,len) \
lock_reg(fd,F_SETLK,F_UNLCK,offset,whence,len)
///返回-1 -- 错误 0 -- 没有锁定 其它 -- 已经锁,返回是拥有锁的进程ID
#define is_read_lockable(fd,offset,whence,len) \
!lock_test(fd,F_RDLCK,offset,whence,len)
#define is_write_lockable(fd,offset,whence,len) \
!lock_test(fd,F_WRLCK,offset,whence,len)
#define my_lock(fd) (writew_lock(fd,0,SEEK_SET,0))
#define my_unlock(fd) (un_lock(fd,0,SEEK_SET,0))
int main(int argc,char **argv)
{
int fd;
long i,seqno;
pid_t pid;
size_t n;
char line[MAXLINE+1];
pid = getpid();
fd = open(SEQFILE,O_RDWR,FILE_MODE);
for(i = 0;i<20; i++)
{
my_lock(fd);
lseek(fd,0L,SEEK_SET);
n = read(fd,line,MAXLINE);
line[n] = '\0';
printf("%s\n",line);
lseek(fd,0L,SEEK_SET);
write(fd,line,strlen(line));
my_unlock(fd);
}
exit(0);
}
int lock_reg(int fd,int cmd,int type,off_t offset,int whence,off_t len)
{
struct flock lock;
lock.l_type = type;
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
return ( fcntl(fd,cmd,&lock));
}
pid_t lock_test(int fd, int type,off_t offset,int whence, off_t len)
{
struct flock lock;
lock.l_type = type;
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
if (fcntl(fd,F_GETLK,&lock) == -1)
return (-1);
if (lock.l_type == F_UNLCK)
return 0;
return(lock.l_pid);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -