[转载] 环境变量的继承,fork、source、exec区别差异

1 minute read

背景

原文

http://zhu8337797.blog.163.com/blog/static/1706175492011671158505/

fork

使用 fork 方式运行 script 时, 就是让 shell(parent process) 产生一个 child
process 去执行该 script, 当 child process 结束后, 会返回 parent process,
但 parent process 的环境是不会因 child process 的改变而改变的.

source

使用 source 方式运行 script 时, 就是让 script 在当前 process 内执行, 而不
是产生一个 child process 来执行. 由于所有执行结果均于当前 process 内完成,
若 script 的环境有所改变, 当然也会改变当前 process 环境了.

exec

使用 exec 方式运行script时, 它和 source 一样, 也是让 script 在当前process
内执行, 但是 process 内的原代码剩下部分将被终止. 同样, process 内的环境随
script 改变而改变.

结论:通常如果我们执行时,都是默认为fork的。大家可以通过pstree命令看看关于父子进程的关系。如上,如果想让父进程得到子进程的环境变量,就是source方式了。

测试脚本练习

[root@orathiz tmp]# vi parent.sh  
#!/bin/bash  
A=B  
echo "PID is parent.sh before child.sh :$$"  
export A  
echo "parent.sh: \$A is $A"  
case $1 in  
       fork)  
               echo "using fork by default..."  
               ./child.sh ;;  
       source)  
               echo "using source..."  
               . ./child.sh ;;  
       exec)  
               echo "using exec..."  
               exec ./child.sh ;;  
esac  
echo "PID is parent.sh after child.sh :$$"  
echo "parent.sh: \$A is $A"  
[root@orathiz tmp]# vi child.sh  
#!/bin/bash  
echo "PID for child.sh:$$"  
echo "child.sh get \$A=$A from parent.sh"  
A=C  
export A  
echo "child.sh: \$A is $A"  

分别执行./parent.sh fork、source和exec得到的结果如下:

[root@orathiz tmp]# ./parent.sh fork  
PID is parent.sh before child.sh :25679  
parent.sh: $A is B  
using fork by default...  
PID for child.sh:25680  
child.sh get $A=B from parent.sh  
child.sh: $A is C  
PID is parent.sh after child.sh :25679  
parent.sh: $A is B  
[root@orathiz tmp]# ./parent.sh source  
PID is parent.sh before child.sh :25731  
parent.sh: $A is B  
using source...  
PID for child.sh:25731  
child.sh get $A=B from parent.sh  
child.sh: $A is C  
PID is parent.sh after child.sh :25731  
parent.sh: $A is C  
[root@orathiz tmp]# ./parent.sh exec  
PID is parent.sh before child.sh :25959  
parent.sh: $A is B  
using exec...  
PID for child.sh:25959  
child.sh get $A=B from parent.sh  
child.sh: $A is C  

查看某个进程的环境变量

cat  /proc/42638/environ|tr '\0' '\n'

参考

https://site.douban.com/196781/widget/notes/12220452/note/261008964/

http://zhu8337797.blog.163.com/blog/static/1706175492011671158505/

Flag Counter

digoal’s 大量PostgreSQL文章入口