好好爱自己!

查看进程id, 父进程id _How do I get the parent process ID of a given child process?

How to get parent pid from a given children pid?

I know I can mannully check it under /proc, I am wonder if there is a smart/better way to achieve this in Ubuntu. Note the parent may or may not be killed.

Thanks

------------------------------------------------------------------------------------------------

Using pstree by command name

Using pstree you can search by the child process name and get the Process ID (PID) along with the parents, grandparents and any children of the child process:

$ pstree -hp | grep sleep
           |-cron(763)---cron(795)---sh(839)---display-auto-br(841)---sleep(8414)

In this case sleep is the child command and it's PID is 8414. It's parent ID is 841 and is called display-auto-brightness. The grandparent is a shell (sh) with a process ID of 839. The great-grandparent is cron with a process ID of 795. The great-great-grandparent is also cron with a process ID of 763.

If you want to search by Process ID of sleep instead of name you can use:

$ pstree -hp | grep 14653
           |-cron(763)---cron(795)---sh(839)---display-auto-br(841)---sleep(14653)

Notice the sleep process ID changed to 14653. The parent (PID 841) sleeps for 1 minute, wakes up for a split second and then starts a new sleep command which gets a new process ID. This is another reason why searching for sleep is easier than searching by process ID.

This code was taken from: Automatically adjust display brightness based on sunrise and sunset and adapted to this question.


To see a nested chain all the way back to boot process use the PID instead of name:

$ pstree -aps 8541
systemd,1 splash fastboot kaslr
  └─cron,763 -f
      └─cron,795 -f
          └─sh,839 -c    /usr/local/bin/display-auto-brightness
              └─display-auto-br,841 /usr/local/bin/display-auto-brightness
                  └─sleep,8541 60

Note: Another minute has passed and the sleep command gets a new PID (8541).

posted @   立志做一个好的程序员  阅读(252)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2017-07-13 很好的网站收集
2017-07-13 What are Unix swap (.swp) files?
2017-07-13 vim的使用

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示