Since you are using linux, you can use flock :
import os import fcntl import time def main():
It does not matter that we left the file open after exiting prog_lock_acq , because when the process ends, it automatically closes the OS. In addition, if you do not specify the LOCK_NB option, the flock call will be blocked until the current current process completes. Depending on your use case, this may be helpful.
Please note that we do not delete the file on exit. It does not matter. The existence of the file does not indicate a living process - blocking. That way, even if you kill your process with kill -9 , the lock will still be released.
However, there is a caveat: if you disconnect the lock file during the execution of the process, when the next instance of the process is launched, it will create a new file that will not block it and will work just fine, breaking our singleton design. You could do something smart using a directory to prevent unlocking, but I'm not sure how cool that would be.
source share