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)' &  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.