-
Notifications
You must be signed in to change notification settings - Fork 0
shell function
qianfan edited this page Oct 17, 2024
·
2 revisions
参考下面的脚本:
#!/bin/sh
echo=/usr/bin/echo
function function1() {
$echo -n "function1"
}
function function2() {
$echo -n "function2:"
function1
}
function function3() {
$echo -n "function3:"
function2
}
function fork2() {
local f1=$(function1)
$echo -n "function2:"
$echo "${f1}"
}
function fork3() {
local f2=$(fork2)
$echo -n "function3:"
$echo "${f2}"
}
case $1 in
fork)
fork3
;;
*)
function3
;;
esac
在输出结果上没有区别, 但是进程的创建方式上有很大区别. 第一种非 fork
的形式, 就是一个扁平化的执行:
$ rptree -- sh shell_function.sh
function3:function2:function1
Running process tree generated by rptree dc90f6d215a52aeaee59
0.000 [5692] rptree -- sh shell_function.sh
|.... 0.000 [5693] sh shell_function.sh
|.... 0.001 [5694] /usr/bin/echo -n function3:
|.... 0.002 [5695] /usr/bin/echo -n function2:
|.... 0.003 [5696] /usr/bin/echo -n function1
第二种脚本中使用 $()
的地方, 都是 fork 进程的方式:
$ rptree -- sh shell_function.sh fork
function3:function2:function1
Running process tree generated by rptree dc90f6d215a52aeaee59
0.000 [5749] rptree -- sh shell_function.sh fork
|.... 0.000 [5750] sh shell_function.sh fork
|.... 0.001 [5751] sh shell_function.sh fork
|.... 0.001 [5752] sh shell_function.sh fork
|.... 0.001 [5753] /usr/bin/echo -n function1
|.... 0.002 [5754] /usr/bin/echo -n function2:
|.... 0.002 [5755] /usr/bin/echo function1
|.... 0.003 [5756] /usr/bin/echo -n function3:
|.... 0.004 [5757] /usr/bin/echo function2:function1