[英]How to wait for parent process to exit in a child?
我想分叉一個進程並等待父進程退出,然后在子進程中執行某些操作。
天真的方式將是這樣一個繁忙的循環:
# BAD WAY!
pid = os.fork()
if pid == 0:
while True:
if os.path.isdir("/proc/%s" % pid):
break
time.sleep(0.1)
# Parent is dead there.
但這很容易受到PID重用問題的影響。 如果在父進程退出並獲得其PID后立即創建另一個進程,則子進程將永遠不會退出。
另一種方法是在特定文件上使用flock()
。 但它不起作用,因為孩子與父母共享相同的鎖。
一個萬無一失的方法是使用一個特殊的技巧:在父級中創建一個管道,在孩子中,你只需要等到你得到一個EOF。
# Good way
read_fd, write_fd = os.pipe()
pid = os.fork()
if pid > 0:
# Close the read pipe, so that only the child is the reader.
os.close(read_fd)
# It is important to voluntarily leak write_fd there,
# so that the kernel will close it for the parent process
# when it will exit, triggering our trick.
elif pid == 0:
# Daemon ourselves first.
os.setsid()
for fd in {0, 1, 2}:
os.close(fd)
# Close the write pipe so that the parent is the only writer.
# This will make sure we then get an EOF when the only writer exits.
os.close(write_fd)
# Now, we're waiting on the read pipe for an EOF.
# PS: the assert is not necessary in production...
assert os.read(read_fd, 1) == ""
os.close(read_fd)
# At this point, the parent is dead.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.