0

I have a file. My application must open it and protect it from writing done by other applications in my operating system.

Is it possible to do such thing? I tried fcntl.flock() but it seems that this lock is working only for my application. Other programs like text editors can write to file without any problems.

Test example

#!/usr/bin/env python3

import time
import fcntl

with open('./somefile.txt', 'r') as f:
    # accquire lock
    fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)

    # some long running operation
    # file should be protected from writes
    # of other programs on this computer
    time.sleep(20)

    # release lock
    fcntl.flock(f, fcntl.LOCK_UN)

How can I lock a file for every application in system except mine?

BPS
  • 1,133
  • 1
  • 17
  • 38

1 Answers1

0

Flock is advisory locking and it's ignored unless specifically checked for.

There are other alternatives that does mandatory locking like this one. Found in this thread and there are some more alternatives in there as well.

Asnear
  • 11
  • 1
  • It seems that any of those links does not contain "mandatory locking", all they just adding cross platform functionality but they all are still advisory file locking methods. – BPS Jan 09 '19 at 14:33