views:

85

answers:

2

I want to do something like this:

try:
    pid = int(file(lock_file, "r").read())
    print "%s exists with pid: %s" % (lock_file, pid)
    if not check_pid(pid):
        print "%s not running. Phantom lock file? Continuing anyways" % pid
    elif wall_time(pid) > 60 * 5:
        print "%s has been running for more than 5 minutes. Killing it" % pid
        os.kill(pid)
    else:
        print "Exiting"
        sys.exit()
except IOError:
    pass

lock = file(lock_file, "w")
lock.write("%s" % os.getpid())
lock.close()

How do I implement wall_time? Do I have to read from /proc or is there a better way?

A: 

Perhaps you could look at the creation time of the lock file. This wouldn't be guaranteed correct, but it would be correct in most cases (and the consequences of getting it wrong are minimal).

Greg Hewgill
Any problems with this? `elif time.time() - os.stat(lock_file).st_mtime > 60 * 5`
Paul Tarjan
I would go with `st_ctime` instead of `st_mtime`, but otherwise that looks fine.
Greg Hewgill
A: 

If you do not want to use the modify time of the lockfile for some reason, you could just write it down in the file:

pid, start_time = map(int, file(lock_file, "r").read().split())
...
lock.write("%s %d" % (os.getpid(), time.time()))
truppo