How to get process PID for manual lock mechanism in Python?

你说的曾经没有我的故事 提交于 2019-12-22 00:35:13

问题


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.



来源:https://stackoverflow.com/questions/10216402/how-to-get-process-pid-for-manual-lock-mechanism-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!