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:
- 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.
- Caveat luser: when you sweep the rug off of
bash's feet using this trick, thebashprompt will continue to have the wrong idea of the current directory, but every other command (not using the$PWDvariable, of course) will operate correctly. - 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.
bashis my bitch, I rule, then you die.