سؤال

I'm writting an app and its in the specification that I need to lock a file everytime I write on it (this file will be read for other apps that other team is working on):

I made the following function:

int lock_file (int fd)
{
    if (fd == -1)
        return -1;
    struct flock file_locker;
    file_locker.l_type = F_WRLCK;
    file_locker.l_whence = SEEK_SET;
    file_locker.l_start = 0;
    file_locker.l_len = 0; //lock the entire file

    int locked = fcntl(fd, F_SETLK, &file_locker);
    if (locked == -1){
        /*handle errors*/
        return 0;
    }
    return 1;
}

I can get the 1 return (means everything is ok) but when I made a test case I could write in the locked file Oo

the test code was:

char *file = "lock_test_ok";
int fd = open(file, O_RDWR);
int locked = lock_file(fd);
/* call popen and try write 'ERROR' in the file */

/* if the file contains ERROR, than fail */
هل كانت مفيدة؟

المحلول

Locking in Unix is advisory: only programs testing the lock will not write in it. (Some offers mandatory locking, but not that way. It usually involves setting up special properties on the locked file.)

نصائح أخرى

The lock is released when the first process exists and its file descriptors are all closed.

Edit: I think I misunderstood the test scenario -- a popen() call won't be following the locking protocol (which is only advisory, and not enforced by the OS), so the write occurs even if the process that called lock_file() still exists and is holding the lock.

In addition to what Jim said, fcntl locks are advisory. They do not prevent anyone from opening and writing to the file. The only thing they do is prevent other processes from acquiring their own fcntl locks.

If you control all writers to the file, this is fine, because you can just have every writer try to lock the file first. Otherwise you're hosed. Unix does not offer any "mandatory" locks (locks that cause open or write to fail).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top