难道fcntl记录锁失效?

来源:互联网 发布:淘宝失效宝贝 编辑:程序博客网 时间:2024/04/30 07:42

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.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; /* F_RDLCK, F_WRLCK, F_UNLCK */
    lock.l_start = offset;
    lock.l_whence = whence;
    lock.l_len = len;

 

    return (fcntl(fd, cmd, &lock));
}

 

int main( void )
{
    int fd = 0;
    char buf[1024] = { 0 };

 

    fd = open("./test.txt", O_RDWR, 0);
 //   printf("lock = %d/n", lock_reg(fd, F_SETLK, F_RDLCK, SEEK_SET, 0, 0));
    lock_reg(fd, F_SETLK, F_WRLCK, 0, SEEK_SET, 0);

    while(1)
    {
        sleep(1);
        read(fd, buf, 1024);
        printf("buf = %s/n", buf);
    }


    return 0;
}

 

 

linux系统中:该程序在运中,使用vim或者gedit对当前目录下test.txt进行编辑成功,但不会马上把文件内容打印出来,下次启动程序会把内容打印出来。

 

freeBSD系统中:该程序运中,使用vi对当前目录下test.txt文件进行编辑,提示为只读文件,但使用w!命令照样可以修改文件内容,也不会马上把内容打印出来,但下次启动程序会把内容打印出来。

 

搞不明白怎么使用,可能是自己理解有问题,继续研究!

原创粉丝点击