How to get process PID for manual lock mechanism i

2020-07-27 05:48发布

问题:

I would like to make a simple locking mechanism in Python without having to rely on the existing libraries for locking (namely fcntl and probably others)

I already have a small stub, but after searching for a bit I couldn't find a good on answer on how to manually create the lock file and put the process PID inside. Here is my stub:

dir_name = "/var/lock/mycompany"
file_name = "myapp.pid"
lock = os.path.join(dir_name, file_name)

if os.path.exists(lock):
    print >> sys.stderr, "already running under %s, exiting..." % lock
    # display process PID contained in the file, not relevant to my question
    sys.exit(ERROR_LOCK)
else:
    # create the file 'lock' and put the process PID inside

How can I get the current process PID and put it inside the lock file? I thought about looking at /proc filesystem but that seems a bit too much for such a simple task.

Thanks.

回答1:

open(lock, 'w').write(os.getpid())



回答2:

http://docs.python.org/library/os.html#os.getpid



回答3:

Don't neglect to convert the result of os.getpid() to a string with str(os.getpid()). write wants a string argument.