同一shell脚本下,后台调用shell函数,子进程PID“$$“不更新的处理

tech2022-12-08  109

同一shell脚本下,后台调用shell函数,子进程PID"$$"不更新的处理

同一shell脚本下,后台调用shell函数,子进程PID"$$"不更新的处理问题原因解决方案

同一shell脚本下,后台调用shell函数,子进程PID"$$"不更新的处理

写shell脚本时遇到了一个奇怪的问题,在同一shell脚本下,后台启动shell函数,子进程获取的$$与父进程相同未更新的问题。 测试代码test.sh如下:

# 输出父进程PID echo "ParentPid:$$" function func1(){ # 输出子进程PID echo "ChildPid:$$" } # 后台运行func1(启动一个子进程) func1 &

输出如下:

[hq@localhost ~]$ sh test.sh ParentPid:110324 ChildPid:110324 [hq@localhost ~]$ ps -ef|grep sleep hq 110326 110325 0 11:00 pts/2 00:00:00 sleep 20s hq 110350 60928 0 11:00 pts/2 00:00:00 grep --color=auto sleep [hq@localhost ~]$ ps -ef|grep 110325 hq 110325 1 0 11:00 pts/2 00:00:00 sh test.sh hq 110326 110325 0 11:00 pts/2 00:00:00 sleep 20s hq 110398 60928 0 11:00 pts/2 00:00:00 grep --color=auto 110325

可以看到,新的进程已启动,PID为110326,但是两次输出的PID一样,子进程的$$未更新

问题原因

在这篇文章中找到了答案->子shell 进程D("$$")

shell中$$获取的是当前shell脚本到PID,后台调用函数时当前shell进程还是父进程,所以$$未更新。

解决方案

启动子进程前,再创建一个shell $() 或 sh

# 输出父进程PID echo "ParentPid:$$" function func1(){ # 输出子进程PID echo "ChildPid:$$" } # 将函数导出,否则子进程无法调用 export -f func1 # 再开一个sh启动函数 sh -c "func1" &

输出结果:

[hq@localhost ~]$ sh test.sh ParentPid:107072 ChildPid:107073
最新回复(0)