启动进程后,如何在子进程中获取父进程的PID? [英] After starting process, how to get parent's PID in the child?
问题描述
在 Python 中,我通过 Popen()
启动了一个新进程,效果很好.现在在子进程中我想找到父进程的 ID.
In Python, I start a new process via Popen()
, which works fine. Now in the child process I want to find the parent's process ID.
实现此目的的最佳方法是什么,也许我可以通过 Popen
构造函数传递 PID,但是如何实现?或者有更好的方法吗?
What is the best way to achieve this, maybe I can pass the PID via the Popen
constructor, but how? Or is there a better way to do so?
PS:如果可能,我更喜欢只使用标准库的解决方案.
PS: If possible I would prefere a solution using only standard libraries.
推荐答案
您可以使用 os.getppid()
:
You can use os.getppid()
:
os.getppid()
Return the parent’s process id.
注意:这仅适用于 Unix,不适用于 Windows.在 Windows 上,您可以使用 os.getpid()
在父进程中,并将 pid 作为参数传递给以 Popen
开头的进程.
Note: this works only on Unix, not on Windows. On Windows you can use os.getpid()
in the parent process and pass the pid as argument to the process you start with Popen
.
Windows 支持 os.getppid
是在 Python 3.2 中添加的.
Windows support for os.getppid
was added in Python 3.2.
这篇关于启动进程后,如何在子进程中获取父进程的PID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!