File lock does not work properly

I have a Thread-extending class that should only run one instance at a time (cross process). For this I am trying to use file locking. Here are the snippets of my code:

class Scanner(Thread):

  def __init__(self, path):
    Thread.__init__(self)
    self.lock_file = open(os.path.join(config.BASEDIR, "scanner.lock"), 'r+')
    fcntl.lockf(self.lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)

  # Stuff omitted

  def run(self):
    logging.info("Starting scan on %s" % self.path)

    # More stuff omitted

    fcntl.lockf(self.lock_file, fcntl.LOCK_UN)

I expected the call to lockfthrow an exception if the thread is Scanneralready running, rather than initializing the object at all. However, I see this in the terminal:

INFO:root:Starting scan on /home/felix/Music
INFO:root:Starting scan on /home/felix/Music
INFO:root:Scan finished
INFO:root:Scan finished

Which assumes that two threads Scannerare running at the same time, no exception is thrown. I am sure that I am missing something really basic, but I can’t understand what it is. Can anyone help?

+3
source share
3 answers

. fcntl.flock() fcntl.lockf(), . , .

+3

r+, . .

w r+a

+2

Along with using the pack, I also had to open the file as follows:

fd = os.open(lockfile, os.O_CREAT | os.O_TRUNC | os.O_WRONLY)

This does not work differently.

0
source

All Articles