Monday, September 2, 2013

How to get the current working directory of a process in Linux

Sometimes we encounter  situations where you need to  find the current working directory of a running process. There are several ways to get this information in a Linux machine.

Method 1:

We can get the current working directory (and more details) of a process with pid $PID, by checking the contents of /proc/$PID folder.

Example:

For a process with process ID 3551

[root@10 ~]# readlink /proc/3551/cwd
/etc/sysconfig/network-scripts

Or with more details,

[root@10 ~]# ll /proc/3551
total 0
dr-xr-xr-x 2 root root 0 Sep  2 21:15 attr
-r-------- 1 root root 0 Sep  2 21:15 auxv
-r--r--r-- 1 root root 0 Sep  2 21:05 cmdline
-rw-r--r-- 1 root root 0 Sep  2 21:15 coredump_filter
-r--r--r-- 1 root root 0 Sep  2 21:15 cpuset
lrwxrwxrwx 1 root root 0 Sep  2 21:15 cwd -> /etc/sysconfig/network-scripts
-r-------- 1 root root 0 Sep  2 21:15 environ
lrwxrwxrwx 1 root root 0 Sep  2 21:05 exe -> /sbin/dhclient
dr-x------ 2 root root 0 Sep  2 21:15 fd
dr-x------ 2 root root 0 Sep  2 21:15 fdinfo
-r--r--r-- 1 root root 0 Sep  2 21:15 io
-r--r--r-- 1 root root 0 Sep  2 21:15 limits
-rw-r--r-- 1 root root 0 Sep  2 21:15 loginuid
-r--r--r-- 1 root root 0 Sep  2 21:15 maps
-rw------- 1 root root 0 Sep  2 21:15 mem
-r--r--r-- 1 root root 0 Sep  2 21:15 mounts
-r-------- 1 root root 0 Sep  2 21:15 mountstats
-rw-r--r-- 1 root root 0 Sep  2 21:15 oom_adj
-r--r--r-- 1 root root 0 Sep  2 21:15 oom_score
lrwxrwxrwx 1 root root 0 Sep  2 21:15 root -> /
-r--r--r-- 1 root root 0 Sep  2 21:15 schedstat
-r--r--r-- 1 root root 0 Sep  2 21:15 smaps
-r--r--r-- 1 root root 0 Sep  2 21:05 stat
-r--r--r-- 1 root root 0 Sep  2 21:15 statm
-r--r--r-- 1 root root 0 Sep  2 21:12 status
dr-xr-xr-x 3 root root 0 Sep  2 21:15 task
-r--r--r-- 1 root root 0 Sep  2 21:15 wchan

Method 2:

Use pwdx command.

Example:

For a process with process ID 3551


[root@10 ~]# pwdx 3551
3551: /etc/sysconfig/network-scripts

Method 3:

Use lsof command.

Example:

For a process with process ID 3551

[root@10 ~]# lsof -p 3551
dhclient  3551      root  cwd       DIR      253,0     4096    1769476 /etc/sysconfig/network-scripts
dhclient  3551      root  rtd       DIR      253,0     4096          2 /
....



~~~


No comments: