4

My end goal is to be able to open a new terminal window (urxvt) directly in the current working directory of the program running in the window currently active.

I'm currently using the shell (Bash), but I don't have anything against alternatives.

So far, I've got the ID of the current active window using xdotool:

wid=$(xdotool getactivewindow)

and the PID of its process using xprop:

pid=$(xprop -id $wid _NET_WM_PID | awk '{print $NF}')

but this is not the PID I'm looking for. I want the PID of the process running in the terminal displayed in that window. For now, I mostly want the case of a bash shell running in that window, but I don't see why it would depend on that.

I can already get CWD from a PID using cwd="$(readlink /proc/$pid/cwd)".

2

Maybe:

readlink "/proc/$(
    pgrep -P "$(xdotool getactivewindow getwindowpid)" | head -n1
  )/cwd"

That is get the pid associated with the window using xdotool, use pgrep to get the list of children of that process, head -n1 to only select the first one, and use readlink to get the working directory.

Will not work for every window. For instance, not for windows from remote clients or that don't provide the window manager with their PID, not for processes by other users.

  • Thanks for the idea to get the children PIDs, and the cleaner way to get the PID of the window. I've posted the full answer in another reply though, so I'll not mark your answer as the accepted one. – 1ace Jun 4 '13 at 10:20
0

Got it! Thanks to Stephane Chazelas for the help. The trick was to look for the child processes... D'oh!

My script is now:

#!/usr/bin/env bash
ppid=$(xdotool getactivewindow getwindowpid) # PID of process in the window
pid=$(pgrep -P $ppid | tail -n1) # PID of the last child
cwd="$(readlink /proc/${pid:-$ppid}/cwd)" # current CWD of pid, or ppid if no pid
cd "$cwd"
"$@"

You can use it by simply prefixing any command with the name of the script, eg. incwd urxvt.

The only caveat is that some programs, like evince, reset their cwd. I doubt there's anything I can do in these cases.

  • Isn't there another caveat: If the window has multiple child PID's and the caller wasn't the most recent? gnome-terminal and Chrome both come to mind. How are you calling this script, isn't there a way to use the script's PPID to at least narrow the field f possibilities? – Bratchley Jun 4 '13 at 10:42
  • My intended use was through a keybinding, so its parent would be the WM (OpenBox in my case). – 1ace Jun 4 '13 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.