How to know the pid of active window

Finally I managed to work get the PID of actively focused window with xdotool

xprop -id `xdotool getwindowfocus` | grep '_NET_WM_PID' | grep -oE '[[:digit:]]*$'

xdpyinfo has, buried in its voluminous output, the window id of the window with the focus (see: Which window has the current focus?). With that, you can use xprop to get the the associated PID.

xprop -id `xdpyinfo | grep -Eo 'window 0x[^,]+' | cut -d" " -f2` | grep PID

Using xdotool's window stack:

xdotool getactivewindow getwindowpid

Bash:

#!/bin/bash
set -e
WINDOW_PID=$(xdotool getactivewindow getwindowpid)
...

Tags:

Window