如何锁定文件以进行O_RDWR的读写访问

时间:2013-03-19 09:36:51

标签: c linux locking fcntl

我找不到关于如何锁定文件以进行读写的答案。

lock.l_type = F_WRLCK //for write.
lock.l_type = F_RDLCK //for read
lock.l_type = F_RDLCK|F_WRLCK //maybe for read/write????

以下代码是否正确?

fd=MyOpenWrite(name,O_RDWR);  //for read/write
//(open file for read/write, but lock for write)
...
fd=MyOpenRead(name,O_RDONLY);  //open and lock for read
...
fd=MyOpenWrite(name,O_CREAT|O_WRONLY|O_TRUNC); //for write
...
fd=MyOpenWrite(name,O_WRONLY|O_APPEND);  //for append

int MyOpenRead(char *name,int flags) {
    int fd;
    struct flock    lock;
    fd = open(name,flags);
    if (fd<0) return -1;
    lock.l_type = F_RDLCK;
    lock.l_start = 0;
    lock.l_whence = SEEK_SET;
    lock.l_len = 0;
    fcntl(fd,F_SETLKW,&lock);
    return fd;
}

int MyOpenWrite(char *name,int flags) {
    int fd;
    struct stat st;
    fd = open(name,flags,S_IREAD|S_IWRITE|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
    if (fd<0) return -1;

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

1 个答案:

答案 0 :(得分:3)

写锁定也会阻止读者。它是一个独占锁,所以只有*所有者才能访问锁定的字节,没有其他人可以通过读或写来访问这些字节。

* fcntl()锁是咨询锁。所以打开文件的任何人如果不合作就可以自由地读/写它,并且还使用fcntl()来获取锁。如果您需要强制锁定,请参阅here