如何获取进程的祖父母ID
如何获取当前进程父进程的进程ID?
一般来说,给定一个进程 ID,我如何获取其父进程 ID?
例如 os.getpid() 可用于获取进程 id,os.getppid() 可用于获取父进程,我如何获取祖父母,
我的目标是 linux(ubuntu) 所以平台特定的答案是可以的。
How can i get process id of the current process's parent?
In general given a process id how can I get its parent process id?
e.g. os.getpid() can be used to get the proccess id, and os.getppid() for the parent, how do I get grandparent,
My target is linux(ubuntu) so platform specific answers are ok.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
通过使用 psutil ( https://github.com/giampaolo/psutil ):
By using psutil ( https://github.com/giampaolo/psutil ):
Linux特定:
linux specific:
我认为你不能以可移植的 Python 方式做到这一点。但有两种可能性。
ps
命令获取,以便您可以对其进行分析。proc
文件系统,则可以打开文件/proc//status
并搜索包含PPid 的行:
,然后对该 PID 执行相同操作。例如,以下脚本将获取您的 PID、PPID 和 PPPID,愿意的权限:
生成:
显然,您必须使用 Python 打开这些文件。
I don't think you can do this in a portable Python fashion. But there are two possibilities.
ps
command so you could analyze that.proc
file systems, you can open the file/proc/<pid>/status
and search for the line containingPPid:
, then do the same for that PID.For example the following script will get you your PID, PPID and PPPID, permissions willing:
produces:
Obviously, you'd have to open those files with Python.
我认为在一般情况下你不能便携地做到这一点。
您需要从进程列表中获取此信息(例如通过 ps 命令),该信息是通过系统特定的方式获取的。
I do not think you can do this portably in the general case.
You need to get this information from the process list (e.g. through the
ps
command), which is obtained in a system-specific way.我查了一下这个作业,但没有找到我想要的东西,所以我会在这里发布。我知道这是很明显的,但它让我困惑了一会儿。如果您是祖父母代码的编写者,您可以:
I looked this up for an assignment and didn't find what I was looking for, so I will post here. I know this is very obvious, but it stumped me for a moment. If you are the one writing the grandparent's code, you can just:
如果您有一个符合 POSIX 标准的“ps”命令,它允许您指定所需的列,如下所示:
ps -o pid,ppid
然后您可以尝试:
现在您可以这样做:
您甚至可以编写一个函数来列出进程的祖先:
If you have a POSIX-compliant 'ps' command, which allows you to specify the columns you want, like this:
ps -o pid,ppid
You could then try:
Now you can do:
You could even write a function to list a process' ancestors: