[Tutor] lockfiles and timestamps and nested if's!
Michael P. Reilly
arcege@speakeasy.net
Thu, 17 May 2001 16:05:56 -0400 (EDT)
kromag@nsacom.net wrote
>
> I am attempting a silly thing. I wish to make a script that will:
>
> 1. Check for the existence of a lockfile.
> 2. Check the age of the lockfile.
>
> Then either:
> Delete the lockfile if it is too old and continue,
> or
> exit gracefully.
>
> I have managed to get myself into a dither here. The script for some reason
> always writes a new lock file and updates the timestamp. Can someone clue me
> in? My brain is full.
>
> import glob
> import time
> import string
> import os
> import socket
>
> now=time.time()
> mybox=socket.gethostname()+'.txt'
> whoa=glob.glob('\tmp\*')
> if whoa==['\tmp\'+mybox]:
> lockfile=open('\tmp\'+mybox, 'r')
> timestamp=lockfile.readline()
> print timestamp
> lockfile.close()
> if timestamp > time.time()-10:
> print 'old lockfile ok',
> else:
> os.remove('\tmp\'+mybox)
>
> else:
> lockfile=open('\tmp\'+mybox, 'w')
> lockfile.write(`now`)
> print 'new lockfile'
> print 'and contiue with the rest of this balderdash!
Off hand, I would say (ignoring the quoting problem), that \tmp\ has
more than just that lockfile in it. I would check with os.path.exists
instead of glob.glob.
Also beware of race conditions; your form of locking isn't necessarily
"safe". On Win32, I believe that os.mkdir() is safe in terms of
guaranteeing who owns the lock.
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |