How to parse /proc/pid/cmdline

前端 未结 7 1905
盖世英雄少女心
盖世英雄少女心 2021-02-01 18:51

I\'m trying to split the cmdline of a process on Linux but it seems I cannot rely on it to be separated by \'\\0\' characters. Do you know why sometimes the \'\\0\' character is

相关标签:
7条回答
  • 2021-02-01 19:23

    use strings

    $ cat /proc/self/cmdline | strings -1
    cat
    /proc/self/cmdline
    
    0 讨论(0)
  • 2021-02-01 19:23

    The /proc/PID/cmdline is always separated by NUL characters.

    To understand spaces, execute this command:

    cat -v /proc/self/cmdline "a b" "c d e"
    

    EDIT: If you really see spaces where there shouldn't be any, perhaps your executable (intentionally or inadvertently) writes to argv[], or is using setproctitle()?

    When the process is started by the kernel, cmdline is NUL-separated, and the kernel code simply copies the range of memory where argv[] was at process startup into the output buffer when you read /proc/PID/cmdline.

    0 讨论(0)
  • 2021-02-01 19:23

    The command line arguments in /proc/PID/cmdline are separated by null bytes. You can use tr to replace them by new lines:

    tr '\0' '\n' < /proc/"$PID"/cmdline
    
    0 讨论(0)
  • 2021-02-01 19:25

    Use

    cat /proc/2634/cmdline | tr "\0" " "
    

    to get the args separated by blanks, as you would see it on a command line.

    0 讨论(0)
  • 2021-02-01 19:44

    Have a look at my answer here. It covers what I found when trying to do this myself.

    Edit: Have a look at this thread on debian-user for a bash script that tries its best to do what you want (look for version 3 of the script in that thread).

    0 讨论(0)
  • 2021-02-01 19:45

    Super-simple (but for only one process, not bulk parsing, etc):

    $ cat /proc/self/cmdline "a b" "cd e" | xargs -0
    

    How it works: by default, xargs just echo'es its input, and switch -0 allows it to read null-separated lines rather than newline-separated ones.

    0 讨论(0)
提交回复
热议问题