如何在子进程在后台启动并且父进程已经退出的情况下,获取父进程的信息?

5
我有一个在前台运行的子进程,他的父进程已经退出了。
如果父进程已经退出,proc/$pid/stat文件中就不再包含原来的父进程ID,而是显示1。
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.......

10
是的,孤儿进程会被 init(pid 1)“收养”。这是有意为之的设计,据我所知,在父进程退出后,无法恢复原始父进程的 pid。 - Frédéric Hamidi
10
如果你硬着头皮想要找出一种方法,进程 ID 最终会被循环使用,因此该数字可能并不意味着你认为的那样。 - jthill
1个回答

1

我认为在父进程执行完之后,你无法知道它的父进程是什么。但也许你可以运行另一个程序来监控原始程序并维护日志文件等。当然,孤儿进程会被init接管。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接