2

Several instances of my script may want to clean up a folder called logs. I want to give access to one script at a time. If another script is in there just ignore the clean up and continue. My implementation is as follows:

lockfile = "LOCKED"
if not os.path.isfile(lockfile):
    open(lockfile, "a").close()

    # start clean up

    os.remove(lockfile)

Is this safe? I can imagine that the if statement evaluates to true before either script has created the lock file. Could this happen? How would you implement such a lock?

Leevi L
  • 1,538
  • 2
  • 13
  • 28
  • you could use a portable lock on your lock file: https://stackoverflow.com/a/490102/6451573 – Jean-François Fabre Nov 29 '18 at 09:52
  • `if not os.path.isfile(lockfile): open(lockfile, "a").close()` is just unsafe because the file could be created after the if and before the open. At least try to open using os.open without CREAT and catch the exception – Jean-François Fabre Nov 29 '18 at 09:55
  • @Jean-FrançoisFabre can you just write it out? not sure what you mean – Leevi L Nov 29 '18 at 10:27
  • 1
    I mean: when you test "isfile", it can NOT exist, then be created then you try to open. It's not atomic. Lookup "atomic file creation in python": https://stackoverflow.com/questions/33223564/atomically-creating-a-file-if-it-doesnt-exist-in-python – Jean-François Fabre Nov 29 '18 at 12:07
  • @Jean-FrançoisFabre I would like to write up an answer using your suggestion but I can't because the question is marked as duplicate – Leevi L Nov 29 '18 at 12:51
  • if the answer is just copying one of the duplicates, then no need to write an answer. If the answer takes bits of stuff & adds something new, I'm ok to reopen. Maybe you could [edit] your question to explain how the duplicates _don't_ answer your question. Then the question is automatically placed in the reopen queue and you don't even need my advice. – Jean-François Fabre Nov 29 '18 at 13:35

0 Answers0