Environment variables of a running process on Unix?

Solution 1:

cat /proc/<pid>/environ

If you want to have pid(s) of a given running executable you can, among a number of other possibilities, use pidof:

AlberT$ pidof sshd   
30690 6512 

EDIT:

I totally quote Dennis Williamson and Teddy comments to achieve a more readable output. My solution is the following:

tr '\0' '\n' < /proc/<pid>/environ

Solution 2:

Since this question has a unix tag and everyone else has done such a great job addressing linux tag, you can get this information on OS X and other BSD-derived systems using

ps -p <PID> -wwwe

or

ps -p <PID> -wwwE

and on Solaris with

/usr/ucb/ps -wwwe <PID>

Solaris also supports the /proc directory if you don't want to remember the obscure ps commmand.


Solution 3:

As others have mentioned, on Linux, you can look in /proc but there are, depending on your kernel version, one or two limits:

First of all, the environ file contains the environment as it looked when the process was spawned. That means that any changes the process might have made to its environment will not be visible in /proc:

$ cat /proc/$$/environ | wc -c
320
$ bash
$ cat /proc/$$/environ | wc -c
1270
$ 

The first shell is a login shell and initially has a very limited environment but grows it by sourcing e.g. .bashrc but /proc does not reflect this. The second shell inherits the larger environment from the start, which it why it shows in /proc.

Also, on older kernels, the contents of the environ file is limited to a page size (4K):

$ cat /proc/$$/environ | wc -c
4096
$ env | wc -c
10343
$ 

Somewhere between 2.6.9 (RHEL4) and 2.6.18 (RHEL5) this limit was removed...


Solution 4:

correct usage of BSD options to do this (at least on linux):

ps e $pid

or

ps auxe  #for all processes

and yes, ps manpage is pretty confusing. (via)


Solution 5:

While rather sparsely documented, the contents of /proc/<pid>/environ will only contain the environment that was used to start the process.

If you need to inspect the current state of a process' environment, one way to do that is by using gdb.

# Start gdb by attaching it to a pid or core file
gdb <executable-file> <pid or core file>

# Run the following script to dump the environment
set variable $foo = (char **) environ
set $i = 0
while ($foo[$i] != 0)
print $foo[$i++]
end