我有一个bash代码,可以给我随机的结果。 我已经将我的代码删除了一些伪代码,如下所示:
#!/usr/bin/bash
function TrapQuit {
echo "Quitting"
}
function SubFunction {
echo "Full function call tree ${FUNCNAME[@]}"
}
function DisPatch {
echo "Running function ${FUNCNAME[0]}"
SubFunction "1"
}
function test {
kill -USR1 $$
}
trap DisPatch USR1
trap TrapQuit EXIT HUP
test &
test &
test &
test &
test &
while true; do
sleep 1
done
基本上,$ {FUNCNAME [@]}应该列出从当前函数到main的所有函数调用。 当我运行此代码时,我会得到随机不同的结果。
好结果是:
Running function DisPatch
Full function call tree SubFunction DisPatch main
Running function DisPatch
Full function call tree SubFunction DisPatch main
Running function DisPatch
Full function call tree SubFunction DisPatch main
Running function DisPatch
Full function call tree SubFunction DisPatch test main
^CRunning function DisPatch
Full function call tree SubFunction DisPatch main
Quitting
奇怪的结果是:
Running function DisPatch
Full function call tree SubFunction DisPatch main
Running function DisPatch
Full function call tree SubFunction DisPatch main
Running function DisPatch
Full function call tree SubFunction DisPatch DisPatch main
Running function DisPatch
Full function call tree SubFunction DisPatch SubFunction DisPatch DisPatch main
Running function DisPatch
Full function call tree SubFunction DisPatch main
^CQuitting
每运行三到五次,我得到了奇怪的结果,其中DisPatch函数在$ {FUNCNAME [@]}中是三次。
DisPatch函数如何在SubFunction的$ {FUNCNAME [@]}中多次结束,似乎DisPatch已递归执行?
感谢您的任何见解。
使用
进行测试GNOS bash,版本4.2.46(1) - 在CentOS 7下发布(x86_64-redhat-linux-gnu)
GNU bash,版本4.3.42(1) - 在Fedora 24下发布(x86_64-redhat-linux-gnu)
答案 0 :(得分:2)
有两个问题。首先,$$
始终是最顶层shell的进程ID;子壳不会重置其值。请改用kill -USR1 $BASHPID
。其次,子进程不继承陷阱。您需要将trap DisPath USR1
移到test
的定义中。
最后,您的test
应该是
function test {
trap DisPatch USR1
kill -USR1 $BASHPID
}