Trace of executed programs called by a Bash script

后端 未结 8 1859
难免孤独
难免孤独 2020-12-13 14:44

A script is misbehaving. I need to know who calls that script, and who calls the calling script, and so on, only by modifying the misbehaving script.

This is similar

相关标签:
8条回答
  • 2020-12-13 15:28

    A simple script I wrote some days ago...

    # 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" | tac | grep -n ":" # using tac to "print in reverse" [3]
    

    ... and a simple test.

    test

    I hope you like it.

    0 讨论(0)
  • 2020-12-13 15:29

    Since you say you can edit the script itself, simply put a:

    ps -ef >/tmp/bash_stack_trace.$$
    

    in it, where the problem is occurring.

    This will create a number of files in your tmp directory that show the entire process list at the time it happened.

    You can then work out which process called which other process by examining this output. This can either be done manually, or automated with something like awk, since the output is regular - you just use those PID and PPID columns to work out the relationships between all the processes you're interested in.

    You'll need to keep an eye on the files, since you'll get one per process so they may have to be managed. Since this is something that should only be done during debugging, most of the time that line will be commented out (preceded by #), so the files won't be created.

    To clean them up, you can simply do:

    rm /tmp/bash_stack_trace.*
    
    0 讨论(0)
提交回复
热议问题