IT博客 联系 聚合 管理  

Blog Stats

文章档案


z314y

 

代码引用的文字,非原创,不知是哪位大侠总结的了,致敬!


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
=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
=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
=from parent.sh
child.sh: $A 
is C

posted on 2009-08-22 15:28 winnie 阅读(382) 评论(0)  编辑 收藏 引用
只有注册用户登录后才能发表评论。