如果子项在后台启动并且父项已经退出,如何知道父进程

MOH*_*MED 5 linux bash shell process ash

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

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
Run Code Online (Sandbox Code Playgroud)

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

test2.sh

#!/bin/sh
echo "test2=$$"
./test3.sh &
Run Code Online (Sandbox Code Playgroud)

test3.sh

#!/bin/sh
echo "test3=$$"
sleep 1000
Run Code Online (Sandbox Code Playgroud)

执行:

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.......
Run Code Online (Sandbox Code Playgroud)

Hri*_*shi 1

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