Get PID of the application running in the active terminal emulator

processterminal-emulatorwindowx11

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)".

Best Answer

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.

Related Question