2

I'm trying to check what happens if a process has an exclusive lock on a file and another process try to write on this file.

Will it fail or just block until the lock is lifted ?

To get an answer, I tried write something but it doesn't seem to be working I also tried to lock the same file from another program but it worked ?? I don't get any error when it should be impossible.

Am I doing something wrong ?

lock.c

    int main()
{
    int fd = open("okas", O_RDWR);
    int n = flock(fd, LOCK_EX);
    if (n == -1 )
    {
        perror("ok");
    }
    while (1)
    {
    }
}

write.c

    int main()
{
    int fd = open("okas", O_RDWR);

    int n = write(fd, "1", 1);
    printf("%d", n);
}
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
Rowooz
  • 31
  • 3
  • 1
    Linux/posix file locks are _advisory_ and not _mandatory_ (like windows). Processes must _cooperate_. `write.c` must also do a `flock` This means that flock will _not_ inhibit read/write but only another flock – Craig Estey Jun 21 '22 at 22:04
  • This is not really a C question: neither `open` nor `flock` are members of the standard library, and `flock` originates in 4.4BSD. You should add `linux` as a tag to the question (or the targetted Unix flavour) – Serge Ballesta Jun 21 '22 at 22:05
  • See: https://en.m.wikipedia.org/wiki/File_locking for an explanation of the various locking models – Craig Estey Jun 21 '22 at 22:24

0 Answers0