Paul Tarjan
Paul Tarjan

Reputation: 50662

Python: Amount of wall time a process has been running

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?

Upvotes: 3

Views: 357

Answers (2)

mthurlin
mthurlin

Reputation: 27315

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()))

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 994649

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).

Upvotes: 1

Related Questions