script/ shell脚本 callstack如何dump

来源:互联网 发布:chemist软件 编辑:程序博客网 时间:2024/05/19 22:27

script加入到需要check的脚本中即可。例如需要check ins_all_mod.shcallstack,将附档中script加入到其最后即可。


# FILE       : sctrace.sh

# LICENSE    : GPL v2.0 (only)
# PURPOSE    : print the recursive callers' list for a script
#              (sort of a process backtrace)
# USAGE      : [in a script] source sctrace.sh
#
# TESTED ON  :
# - Linux, x86 32-bit, Bash 3.2.39(1)-release


# REFERENCES:
# [1]: http://tldp.org/LDP/abs/html/internalvariables.html#PROCCID
# [2]: http://linux.die.net/man/5/proc
# [3]: http://linux.about.com/library/cmd/blcmdl1_tac.htm


#! /bin/bash


TRACE=""
CP=$$ # PID of the script itself [1]


while true # safe because "all starts with init..."
do
        CMDLINE=$(cat /proc/$CP/cmdline)
        PP=$(grep PPid /proc/$CP/status | awk '{ print $2; }') # [2]
        TRACE="$TRACE [$CP]:$CMDLINE\n"
        if [ "$CP" == "1" ]; then # we reach 'init' [PID 1] => backtrace end
                break
        fi
        CP=$PP
done
echo "Backtrace of '$0'"
echo -en "$TRACE" | grep -n ":" # using tac to "print in reverse" [3]
0 0