File content and lock

Viewed 45

I found this code on the web which is able to lock a file and it works.

/*
** lockdemo.c -- shows off your system's file locking.  Rated R.
*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
                     /* l_type   l_whence  l_start  l_len  l_pid   */
    struct flock fl = { F_WRLCK, SEEK_SET, 0,       0,     0 };
    int fd;

    fl.l_pid = getpid();

    if (argc > 1) 
        fl.l_type = F_RDLCK;

    if ((fd = open("lockdemo.c", O_RDWR)) == -1) {
        perror("open");
        exit(1);
    }

    printf("Press <RETURN> to try to get lock: ");
    getchar();
    printf("Trying to get lock...");

    if (fcntl(fd, F_SETLKW, &fl) == -1) {
        perror("fcntl");
        exit(1);
    }

    printf("got lock\n");
    printf("Press <RETURN> to release lock: ");
    getchar();

    fl.l_type = F_UNLCK;  /* set to unlock same region */

    if (fcntl(fd, F_SETLK, &fl) == -1) {
        perror("fcntl");
        exit(1);
    }

    printf("Unlocked.\n");

    close(fd);
} 

For my use case it's not enough.
While the file is locked, I am able to append data to lockdemo.c and I'd like to prevent that.
How can I do?

Regards

1 Answers

You can't.

Unix file locking is strictly "advisory," meaning that it only interacts with itself. Any process can open, read, write, truncate, etc. a locked file and as long as it doesn't call one of the locking functions it won't even notice that the lock exists.

This was an intentional design decision, made many years ago -- people can and do argue about whether it was the right design decision, but it's not going to be changed now.

If you tell us more about your larger problem, we might be able to suggest alternative approaches.

Related