如何在Python中获取用于手动锁定机制的进程PID? [英] How to get process PID for manual lock mechanism in Python?
问题描述
我想在Python中建立一种简单的锁定机制,而不必依赖现有的库进行锁定(即fcntl
以及其他可能的库)
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)
我已经有一个小存根,但经过一番搜索后,我找不到如何手动创建锁定文件并将进程PID放入其中的良好答案.这是我的存根:
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
如何获取当前的进程PID并将其放在lock
文件中?我考虑过要查看/proc
文件系统,但是对于这样一个简单的任务来说,这似乎有点太多了.
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.
谢谢.
推荐答案
open(lock, 'w').write(os.getpid())
这篇关于如何在Python中获取用于手动锁定机制的进程PID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!