首页 > 代码库 > fork exec source的区别

fork exec source的区别

参考:http://www.cnblogs.com/bkygg/p/5023072.html

1:fork  运行的时候开一个sub_shell 执行调用的脚本,sub_shell执行的时候,parent_shell还在。sub_shell执行完毕后返回parent_shell。sub_shell从parent_shell继承环境变量。但是sub_shell中的变量不会带回parent_shell。在子命令执行完后再执行父命令,子级的环境变量不会影响到父级

2:exec 执行子级的命令后,不再执行父级的后面的命令
   
3:source 执行子级命令后继续执行父级的命令,同时子级设置的环境变量会影响到父级的环境变量
      与fork的区别是不新开一个sub_shell来执行被调用的脚本,而是在同一个shell中执行,所有被调用的脚本中的声明的变量和环境变量,都可以在主脚本中得到使用
 
例子理解:
1.sh
#!/bin/bashA=B#$$表示当前进程的PIDecho "PID for 1.sh before exec/source/fork:$$"export A echo "1.sh: \$A is $A"case $1 in    exec)         echo "using exec......"         exec ./2.sh;;    source)         echo "using source......"         source ./2.sh;;    *)         echo "using fork by default......"         ./2.sh;;esacecho "PID for 1.sh after exec/source/fork:$$"echo "1.sh: \$A is $A"~                    

 

2.sh

#!/bin/bashecho "PID for 2.sh:$$"echo "2.sh get \$A=$A from 1.sh"A=Cexport Aecho "2.sh:\$A is $A"

 

执行的结果:

[root@lile shell]# ./1.sh forkPID for 1.sh before exec/source/fork:218521.sh: $A is Busing fork by default......PID for 2.sh:218532.sh get $A=B from 1.sh2.sh:$A is CPID for 1.sh after exec/source/fork:218521.sh: $A is B
[root@lile shell]# ./1.sh sourcePID for 1.sh before exec/source/fork:218621.sh: $A is Busing source......PID for 2.sh:218622.sh get $A=B from 1.sh2.sh:$A is CPID for 1.sh after exec/source/fork:218621.sh: $A is C
[root@lile shell]# ./1.sh execPID for 1.sh before exec/source/fork:218631.sh: $A is Busing exec......PID for 2.sh:218632.sh get $A=B from 1.sh2.sh:$A is C

 

 

fork exec source的区别