fork exec source的区别

时间:2024-12-17 20:37:26

参考: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/bash

A=B
#$$表示当前进程的PID
echo "PID for 1.sh before exec/source/fork:$$"
export A
echo "1.sh: \$A is $A"
case $ in
exec)
echo "using exec......"
exec ./.sh;;
source)
echo "using source......"
source ./.sh;;
*)
echo "using fork by default......"
./.sh;;
esac
echo "PID for 1.sh after exec/source/fork:$$"
echo "1.sh: \$A is $A"
~

2.sh

#!/bin/bash
echo "PID for 2.sh:$$"
echo "2.sh get \$A=$A from 1.sh"
A=C
export A
echo "2.sh:\$A is $A"

执行的结果:

[root@lile shell]# ./.sh fork
PID for .sh before exec/source/fork:
.sh: $A is B
using fork by default......
PID for .sh:
.sh get $A=B from .sh
.sh:$A is C
PID for .sh after exec/source/fork:
.sh: $A is B
[root@lile shell]# ./.sh source
PID for .sh before exec/source/fork:
.sh: $A is B
using source......
PID for .sh:
.sh get $A=B from .sh
.sh:$A is C
PID for .sh after exec/source/fork:
.sh: $A is C
[root@lile shell]# ./.sh exec
PID for .sh before exec/source/fork:
.sh: $A is B
using exec......
PID for .sh:
.sh get $A=B from .sh
.sh:$A is C