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

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


本文链接:http://www.52zhe.cn/read.php/61.htm
本文作者:kook(若就博客内所涉及的技术问题交流,请用下面的MSN或Gmail联系我)
联系方式:(MSN:kook#live.com) (Google talk:kookliu)
没有版权:GNU,转载时请注明“转载人”欠本人一顿饭,来日见面之时兑现!谢谢合作!
Tags: , ,
by kook | 分类: SHELL | 评论(0) | 引用(0) | 阅读(2512)
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]