[RndTbl] Find the CWD and environment variables for a running process...

Sean Cody sean at tinfoilhat.ca
Fri Nov 29 23:49:52 CST 2013


Someone asked on #openbsd (freenode) how to get a running process' current working directory as well as it's environment variables...

Interesting problem.  
Environment variables are easy but the current working directory of a running process requires a bit more thought.

Solution (w's are for column width truncation) for PID's environment:
ps -p `pgrep tmux` -wwwwwe 

eg:
sean at _:~$sudo ps -p `pgrep irssi` -wwwwwe
  PID TT  STAT       TIME COMMAND
14485 p0  S+      4:41.35 _=/usr/local/bin/irssi LOGNAME=sean HOME=/home/sean MAIL=/var/mail/sean TMUX=/tmp/tmux-1000/default,4913,0 PATH=/home/sean/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/usr/games:. TMUX_PANE=%0 TERM=screen SHELL=/bin/ksh USER=sean (irssi)

For the working directory of the process:

sudo lsof -p `pgrep irssi` awk '/cwd/{print "find "$9" -inum "$8" | head -n 1"}' | sudo sh

eg.
sean at _:~$sudo lsof -p `pgrep irssi` | awk '/cwd/{print "find "$9" -inum "$8" | head -n 1"}' | sudo sh
/home/sean

Anyways it was an interesting problem so I figured worthy to share.

Unfortunately I couldn't think of a way to doing it without lsof and sticking with base install and I didn't want to mount /proc...

In Linux you can get a tool called 'pwdx' but that isn't portable, also linux's procfs also includes a cwd file in each process directory.

-- 
Sean






More information about the Roundtable mailing list