How to implement the functionality of lockfile command
<p>I'm trying to implement a filesystem-based lock for a software, which runs on a cluster. The underlying shared filesystem is implemented using <a href="https://en.wikipedia.org/wiki/Distributed_Replicated_Block_Device" rel="nofollow">DRBD</a>, so synchronicity can be considered guaranteed. My current implementation looks like the following:</p>

<pre><code># check the lock file                                                                                                 
if os.path.isfile(lockfile):                                                                                       
    if time.time() - os.path.getmtime(lockfile) &gt; 3600:                                                             
        logInfo('lock is older than 3600s, removing it and going on collecting result.')                           
        os.remove(lockfile)                                                                                        
    else:                                                                                                             
        logInfo('Previous action is still on-going, please wait until it\'s finished or timeout.')
        sys.exit(1)

# create the lock file                                                                                                
open(lockfile, 'w').close();
</code></pre>

<p>Clearly, situations may occur when multiple instances of the script running on different machines in the cluster may unanimously consider the system unlocked, create the lockfile and perform the operations that would require mutual exclusion.</p>

<p>So to sum it up, I need a locking facility which is filesystem-based, and lock check and creation together forms an atomic operation.</p>

<p>The same functionality can be achieved in a shell script using the <a href="http://linux.die.net/man/1/lockfile" rel="nofollow">lockfile</a> command.</p>