- 论坛徽章:
- 0
|
回复 14# waker
通过看了相关的贴,我总结一下我对fork产生子进程和exec运行命令的理解:
用户输入一个命令后或者脚本名字就会发生系统调用,如果该命令是shell的内置命令就会调用当前的shell去解析它,如果是外部命令就会产生一个子shell去exec它.
fork创建子进程的过程,会产生对自己的一个副本,该副本包含了环境变量/权限等等的信息,子进程会继承该副本的相关东西。
exec 是在产生子进程后,运行该命令,子shell就会以他的名字作为参数来来运行该命令.该进程的pid就是该子shell的PID.- osssvr-1:~/test # cat select.sh
- #!/bin/bash
-
- PS3='Choose your favorite vegetable: '
- echo $$
- select vegetable in "beans" "carrots" "potatoes" "onions" "rutabagas"
- do
- echo
- echo "Your favorite veggie is $vegetable."
- echo "Yuck!
- done
- exit 0
- osssvr-1:~/test # ./select.sh
- 1) beans
- 2) carrots
- 3) potatoes
- 4) onions
- 5) rutabagas
- Choose your favorite vegetable
复制代码 在另外个终端里使用ps来查看,- osssvr-1:~ # ps -ef|grep sele
- root 30693 6168 0 10:05 pts/3 00:00:00 /bin/bash ./select.sh
复制代码 在exec的时候是使用/bin/bash这个命令 以./select.sh作为参数来实现的.
那我就以(./select.sh;echo $$)来解释下我自己的理解,望各位指导下我理解是否正确.
在一个终端里运行(./select.sh;echo $$)- osssvr-1:~/test # (./select.sh;echo $$)
- 7930
- 1) beans
- 2) carrots
- 3) potatoes
- 4) onions
- 5) rutabagas
- Choose your favorite vegetable: 2
- +++++++++++++++++++++++++++++++++++++
- +Your favorite veggie is carrots.+
- +Yuck! +
- +++++++++++++++++++++++++++++++++++++
- 6168
复制代码 在另外个终端里使用ps查看:- osssvr-1:~ # ps -ef|grep sele
- root 7930 7929 0 10:10 pts/3 00:00:00 /bin/bash ./select.sh
- osssvr-1:~ # ps -ef|grep 7929
- root 7929 6168 0 10:10 pts/3 00:00:00 -bash
- root 7930 7929 0 10:10 pts/3 00:00:00 /bin/bash ./select.sh
复制代码 系统调用时()会产生一个sub shell,来处理()里面的命令,在运行./select.sh的时候,也产生了个subshell来运行select.sh脚本.所以./select.sh的$$为7930,这个运行完成后,会调用exit,返回个状态码,唤醒
()产生的sub shell,(./select.sh;echo $$)里面的$$乃是继承了()该sub shell的父shell副本里面的信息.
这样理解对吗? |
|