I can't find an answer on how to lock a file for read-write.

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????

Is the code below correct?

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;
}
有帮助吗?

解决方案

A write lock also blocks readers. It is an exclusive lock so only* the owner can access the locked bytes, and no-one else can access those bytes, be it by reading or writing.

* fcntl() locks are advisory locks. So anyone else that opens the file can freely read/write to it if they do not co-operate and also uses fcntl() to grab the locks. See here if you need mandatory locking

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top