How to get the command line args passed to a running process on unix/linux systems?

后端 未结 13 638
梦谈多话
梦谈多话 2020-11-30 16:57

On SunOS there is pargs command that prints the command line arguments passed to the running process.

Is there is any similar command on other Unix env

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 17:11

    On Linux, with bash, to output as quoted args so you can edit the command and rerun it

    On Solaris, with bash (tested with 3.2.51(1)-release) and without gnu userland:

    IFS=$'\002' tmpargs=( $( pargs "${pid}" \
        | /usr/bin/sed -n 's/^argv\[[0-9]\{1,\}\]: //gp' \
        | tr '\n' '\002' ) )
    for tmparg in "${tmpargs[@]}"; do
        printf "%q " "$( echo -e "${tmparg}" )"
    done; echo
    

    Linux bash Example (paste in terminal):

    {
    ## setup intial args
    argv=( /bin/bash -c '{ /usr/bin/sleep 10; echo; }' /dev/null 'BEGIN {system("sleep 2")}' "this is" \
        "some" "args "$'\n'" that" $'\000' $'\002' "need" "quot"$'\t'"ing" )
    
    ## run in background
    "${argv[@]}" &
    
    ## recover into eval string that assigns it to argv_recovered
    eval_me=$(
        printf "argv_recovered=( "
        

    Output:

    MATCH
    

    Solaris Bash Example:

    {
    ## setup intial args
    argv=( /bin/bash -c '{ /usr/bin/sleep 10; echo; }' /dev/null 'BEGIN {system("sleep 2")}' "this is" \
        "some" "args "$'\n'" that" $'\000' $'\002' "need" "quot"$'\t'"ing" )
    
    ## run in background
    "${argv[@]}" &
    pargs "${!}"
    ps -fp "${!}"
    
    declare -p tmpargs
    eval_me=$(
        printf "argv_recovered=( "
        IFS=$'\002' tmpargs=( $( pargs "${!}" \
            | /usr/bin/sed -n 's/^argv\[[0-9]\{1,\}\]: //gp' \
            | tr '\n' '\002' ) )
        for tmparg in "${tmpargs[@]}"; do
            printf "%q " "$( echo -e "${tmparg}" )"
        done; echo
        printf " )\n"
    )
    
    ## do eval
    eval "${eval_me}"
    
    
    ## verify match
    if [ "$( declare -p argv )" == "$( declare -p argv_recovered | sed 's/argv_recovered/argv/' )" ];
    then
        echo MATCH
    else
        echo NO MATCH
    fi
    }
    

    Output:

    MATCH
    

提交回复
热议问题