Reading the environment variables of another process

If you need to read the environment variables of an arbitrary process, the /proc filesystem makes this easy on Linux. The environment variables are shown in /proc/PID/environ:

$ cat /proc/19065/environ
DISPLAY=localhost:0.0SHELL=/bin/bashPWD=/home/phil...

In a shell, it will just look like the variables are smooshed together. They're actually separated by \0 (null character), which you can see if you're manipulating this data in some programming language or using a proper text editor:

C-u M-! cat /proc/19065/environ RET

DISPLAY=localhost:0.0^@SHELL=/bin/bash^@PWD=/home/phil...

[Update: ps can also be made to show the environment in a manner which is more human-readable but slightly less machine-readable; see comments.]

(Found via a Stack Overflow post about changing another process's environment, which is much more difficult.)

3 comments:

  1. What about ps -e ?

    ReplyDelete
  2. Anonymous: thanks for the tip (wish I had thought to use ps)!

    Just to follow up, "ps e" (no dash) instructs ps to print the environment after each command, and something like "ps e -ww -p 19226" will print the original command and a space-delimited list of the environment variables for a single process.

    ReplyDelete
  3. cat /proc/(pid)/environ | tr '\0' '\n'

    is more human-readable as well.

    ReplyDelete