Changing the working directory of a running process

Here’s how to change the working directory of a running process.

Why would you want to do this ? Say you need to un-mount a filesystem (NFS, ext4, CIFS whatever) however there is an open filehandle(file descriptor) from a resident process preventing you from un-mounting the filesystem, and you can’t afford to kill the process, then under certain situations, you can temporarily change the cwd, unmount/remount the filesystem, and then change the cwd for that process back to what it was.

Emulate a program which has a cwd (current working directory) using a python 1-liner.

# python -c 'import os, time; os.chdir("/var/tmp"); time.sleep(240)' &
[1] 22569

# lsof -p 22569 | grep cwd
python  22569 root  cwd    DIR   0,21     4096 41198554 /var/tmp

## This is the only open filehandle on our mountpoint
# lsof -w /var/tmp
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
python  22569 root  cwd    DIR   0,21     4096 41198554 /var/tmp

# ls -ldi /var/tmp
41198554 drwxrwxrwt 4 root root 4096 Apr 23 03:50 /var/tmp

Change the cwd using the GNU debugger.

# gdb -q -p 22569
(gdb) call (int) chdir("/tmp")
(gdb) detach
(gdb) quit

## Check that it worked.
# lsof -p 22569 | grep cwd
python  22569 root  cwd    DIR   0,21     4096 40861717 /tmp

## Final check that there are no new processes which have open filehandles under our mountpoint.
# lsof -w /var/tmp
# ls -ldi /tmp
40861717 drwxrwxrwt 5 root root 4096 Apr 23 03:49 /tmp

Now you can unmount/remount the filesystem.

Advertisements
This entry was posted in linux. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s