Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since you're using linux, you can make use of <a href="http://docs.python.org/2/library/fcntl.html#fcntl.flock" rel="nofollow"><code>flock</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import os import fcntl import time def main(): # acquire the prog lock if not prog_lock_acq('singleton.lock'): print("another instance is running") exit(1) print("program is running-press Ctrl+C to stop") while True: time.sleep(10) def prog_lock_acq(lpath): fd = None try: fd = os.open(lpath, os.O_CREAT) fcntl.flock(fd, fcntl.LOCK_NB | fcntl.LOCK_EX) return True except (OSError, IOError): if fd: os.close(fd) return False if __name__ == '__main__': main() </code></pre> <p>It doesn't matter that we left the file open after exiting the <code>prog_lock_acq</code> because when the process exits, it will be automatically closed by the OS. Also, if you leave out <code>LOCK_NB</code> option, the <code>flock</code> call will block until the current running process quits. Depending on your use case, that might be useful.</p> <p>Note that we're not deleting the file on exit. It doesn't matter. Existence of the file doesn't indicate a live process—the lock does. So even if you kill your process with <code>kill -9</code>, the lock is still released.</p> <p>There is however a caveat: if you unlink the lock file while the process is running, when the next instance of the process is run, it will create a new file which will have no lock on it and will run just fine which will violate our singleton design. You might be able to do something clever with a directory to prevent unlinking but I'm not sure how robust that would be.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload