How to know the pid of active (focused) window?

I want to write a script in which it is necessary to know whether the user is actively using a program [browsing internet with somthing say firefox] or doing something else [writing text with something say gedit]

In my case i want to download big files but don't want to hurt browsering speed. so when i browse the active window is of firefox and i want to stop downloading. When i read pdf active window is of pdf reader and i want to resume download. That's it.


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:]]*$'
| improve this answer | |
  • I take it you got xprop -id ... working? – Ternary Feb 6 '13 at 21:10

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
| improve this answer | |
  • 1
    Sorry, No output on 10.04 – totti Jan 25 '13 at 9:37
  • xdpyinfo | grep -Eo 'window 0x[^,]+' | cut -d" " -f2 output 0x3e00122 – totti Jan 30 '13 at 13:27
  • what does xprop -id 0x3e00122 (or whatever your new current window id is) give you? – Ternary Jan 30 '13 at 17:40
  • 1
    It looks like some windows don't support _NET_WM_PID, but firefox and evince both seem to – Ternary Jan 30 '13 at 17:55
  • and in this case you might find useful to take a look at xprop -id [active window] | grep WM_CLASS – Ternary Jan 30 '13 at 18:17

Using xdotool's window stack:

xdotool getactivewindow getwindowpid


set -e
WINDOW_PID=$(xdotool getactivewindow getwindowpid)
| improve this answer | |


xdotool getwindowpid `xdotool getactivewindow`


xdotool getwindowpid (xdotool getactivewindow)
| improve this answer | |

You can install wmctrl then use it to list all windows, wmctrl -l.

| improve this answer | |
  • 3
    This is a bit too brief to be helpful I think. Could you extend your answer to include some steps to take on how to get the active window for example? Or how to use the output in scripting, etc. – gertvdijk Jan 20 '13 at 20:42
  • I'm afraid I can't help you there, I too am stuck on how to manipulate the output into something useful. Sorry. – Henry Gibson Jan 30 '13 at 18:49

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.