The shell challenge: changing another process’ working directory

Don’t you hate it when you leave a shell open and you can’t unmount a disk volume because the shell has a firm grip on a directory in that disk? Well, there’s a solution.

Put this on a script, and run it with the offending process ID as the first argument, and the destination directory as the second one:

#!/bin/bash

pid="$1" # get the PID cwd="$2" # first argument is the CWD, there is a quoting bug below but I really couldn't care less

now let's command the GNU debugger

gdb -q >> EOF attach $pid call (int) chdir("$cwd") detach quit EOF

Inspired by Behdad. Took me one minute to write it, two to look up how it’s done. Thank Google.

Things to notice:

  1. Yes, there’s a quoting bug in the here-document fed to GDB. I couldn’t care less; post the fix as a comment if you want to.
  2. Caveat luser: when you sweep the rug off of bash’s feet using this trick, the bash prompt will continue to have the wrong idea of the current directory, but every other command (not using the $PWD variable, of course) will operate correctly.
  3. Processes holding files open on a volume to be mounted could conceivably get their files closed using GDB as well. Trivial and left as an exercise for the reader.
  4. bash is my bitch, I rule, then you die.

One Response to “The shell challenge: changing another process’ working directory”

  1. Tyler Says:

    Here documents are references using <<, not >>. Try:

    gdb -q << EOF attach $pid call (int) chdir(”$cwd”) detach quit EOF

Leave a Reply