Advanced Programming in UNIX Environment Episode 72

本文介绍了一种使用fcntl函数进行文件锁定的C语言实现,包括设置读写锁、测试锁定状态及死锁检测的方法。通过具体示例展示了如何在父子进程中分别锁定文件的不同部分,以及如何检测整个文件的写锁。
#include "apue.h"
#include <fcntl.h>

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);
}

Function to test for a locking condition

#include "apue.h"
#include <fcntl.h>

int lock_test(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;

    if(fcntl(fd,F_GETLK,&lock)<0)
        err_sys("fcntl error");
    
    if(lock.l_type==F_UNLCK)
        return 0;

    return lock.l_pid;
}

Function to test for a locking condition

#include "apue.h"
#include <fcntl.h>

static void lock_byte(const char *name, int fd, off_t offset)
{
    if(writew_lock(fd,offset, SEEK_SET,1)<0)
        err_sys("%s: writew_lock error", name);

    printf("%s: got the lock, byte %lld\n",name, (long long) offset);
}

int main(void)
{
    int fd;
    pid_t pid;

    if((fd=creat("templock",FILE_MODE))<0)
        err_sys("creat error");
    if(write(fd,"ab",2)!=2)
        err_sys("write error");

    TELL_WAIT();
    if((pid=fork())<0)
    {
        err_sys("fork error");
    }
    else if(pid==0)
    {
        lockabyte("child",fd,0);
        TELL_PARENT(getppid());
        WAIT_PARENT();
        lockabyte("child",fd,1);
    }
    else
    {
        lockabyte("parent",fd,1);
        TELL_CHILD(pid);
        WAIT_CHILD();
        lockabyte("parent",fd,0);
    }

    return 0;
}

Example of deadlock detection

#include "apue.h"
#include <fcntl.h>

int lockfile(int fd)
{
    struct flock fl;

    fl.l_type=F_WRLCK;
    fl.l_start=0;
    fl.l_whence=SEEK_SET;
    fl.l_len=0;
    return fcntl(fd,F_SETFLK,&fl);
}

Place a write lock on an entire file

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值