Chapter 14__高级IO


struct flock {
short l_type; /* F_RDLCK, F_WRLCK, or F_UNLCK */
short l_whence; /* SEEK_SET, SEEK_CUR, SEEK_END */
OFF_T l_start; /* starting offset relative to l_whence */
OFF_T l_len; /* len == 0 means "until end of file" */
pid_t l_pid; /* Process ID of the process holding the lock,
  returned with F_GETLK */
};

关于struct flock,锁的范围是这么算的
(l_whence + l_start) ~ (l_whence + l_start + l_len)
// 不同的系统,对定义的flock结构,可能不同。


#include <stdio.h>
#include <fcntl.h>
#include <sys/file.h>
#include <stdlib.h>
#include <unistd.h>

void printLockName(int lockType)
{
printf("lock type = %d\n", lockType);
switch (lockType)
{
case F_RDLCK : printf("lock type is F_RDLCK\n"); break;
case F_WRLCK : printf("lock type is F_WRLCK\n"); break;
case F_UNLCK : printf("lock type is F_UNLCK\n"); break;
default : printf("not lock type !\n");
}
}

void setFlock(struct flock *lock, int type, off_t offset, int whence, off_t len)
{
lock->l_type = type;
lock->l_start = offset;
lock->l_whence = whence;
lock->l_len = len;
}

int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
setFlock(&lock, type, offset, whence, 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;
setFlock(&lock, type, offset, whence, len);

if (fcntl(fd, F_GETLK, &lock) < 0)
printf("fcntl error");

printLockName(lock.l_type);
if (lock.l_type == F_UNLCK)
return 0;

return lock.l_pid;
}

void putexit(char *p)
{
printf("%s\n", p);
exit(1);
}


#include <stdio.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
int fd = open("/home/long/myc/tem.file", O_RDONLY);
if (fd < 0)
putexit("open file error!");

if (lock_reg(fd, F_SETLK, F_RDLCK, 0, SEEK_SET, 0) == 0)
printf("lock_reg OK\n");

printf("getpid() = %d\n", getpid());
sleep(10);
close(fd);
return 0;
}


#include <stdio.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
int fd = open("/home/long/myc/tem.file", O_WRONLY);
if (fd < 0)
putexit("open file error!");

int pid = -1;
pid = lock_test(fd, F_WRLCK, 0, SEEK_SET, 0);
printf("lock pid = %d\n", pid);

sleep(10);
char buf[] = "hello\0";
if(write(fd, buf, sizeof(buf)) < 0)
perror("wrire error");

close(fd);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值