【问题标题】:How to know the parent process if the child is launched in background and the parent is already exited如果子进程在后台启动并且父进程已经退出,如何知道父进程
【发布时间】:2013-09-06 15:36:53
【问题描述】:

我有一个子进程在前台运行,他的父亲已经退出。

如果父进程已经退出,proc/$pid/stat 文件将不再包含父进程 pid,它会显示 1 而不是原始父进程进程 pid

linux$cat /proc/6267/stat
6267 (test3.sh) S 1 6265 ......
#                 ^
#                 |
#        I expected to get the origin parent pid but I get 1

为了快速重现这种行为,我们可以使用以下脚本

test2.sh

#!/bin/sh
echo "test2=$$"
./test3.sh &

test3.sh

#!/bin/sh
echo "test3=$$"
sleep 1000

执行:

linux$ ./test2.sh
test2=6318
test3=6319
linux$ ps aux | grep test
 6319 root      1484 S    {test3.sh} /bin/sh ./test3.sh
linux$ cat /proc/6319/stat
6319 (test3.sh) S 1 6318 2138 34816 6.......

【问题讨论】:

  • 是的,孤立的进程被init(pid 1)“采用”。这是设计使然,据我所知,一旦父进程退出,就无法恢复原始父 pid。
  • ...如果您确实以某种方式拼凑在一起,则 pid 最终会被回收,因此该数字可能与您认为的意思不同。

标签: linux bash shell process ash


【解决方案1】:

我认为在(父级)完成执行后您无法知道进程的父级。但是也许您可以运行另一个程序来监视您的原始程序并维护日志文件或其他内容。孤儿进程当然会被 init 采用。

【讨论】:

    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 2010-09-21
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    相关资源
    最近更新 更多