How to parse /proc/pid/cmdline

Viewed 37811

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 used as separator and sometimes it is a regular space?

Do you know any other ways of retrieving the executable name and the path to it? I have been trying to get this information with 'ps' but it always returns the full command line and the executable name is truncated.

Thanks.

8 Answers

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.

Executable name:

cat /proc/${pid}/comm

Executable path:

readlink -f /proc/${pid}/exe

If you have a recent bash, you can use mapfile to split the command line into its arguments and put them in an array "command_line" like this:

mapfile -d '' -t command_line < "/proc/${pid}/cmdline"

Much more about /proc/ here: proc(5) — Linux manual page

Related