「Linux」- 通过进程ID切换到窗口

内容简介

本文将介绍:在桌面环境下,如何通过进程ID切换到对应的窗口。

问题描述

当你发现某个窗口占用资源(比如CPU、内存等等)非常多时,如何才能快速找到对应的窗口呢?在多数情况下,直接查看进程正在执行的命令,就能找到对应的窗口。

但是有些情况下,比如同一个程序运行了多个实例(比如打开多个浏览器实例),怎样才能确定是哪一个占用资源呢?

这也是本文要介绍的内容:在桌面环境下,如何通过进程ID切换到对应的窗口。

解决办法

#1 找到“问题”进程

通过top、ps命令,找到资源占用较多的进程,得到进程的PID值,这里不再介绍。

#2 找到对应窗口

#!/bin/sh

cat <<EOF > /tmp/find-window.sh
#!/bin/sh

findpid=$1

known_windows=$(xwininfo -root -children|sed -e 's/^ *//'|grep -E "^0x"|awk '{ print $1 }')

for id in ${known_windows}
do
    xp=$(xprop -id $id _NET_WM_PID)
    if test $? -eq 0; then
        pid=$(xprop -id $id _NET_WM_PID|cut -d'=' -f2|tr -d ' ')

        if test "x${pid}" = x${findpid}
        then
            echo "Windows Id: $id"
            echo "##################################"
            xprop -id $id
        fi
    fi
done
EOF

# 找到窗口的ID值,形如「0x5a00001」格式。
sh /tmp/find-window.sh "<PID>"

#3 切换到该窗口

使用wmctl可以切换到该窗口,但前提是「窗口管理器」要符合EWMH标准:

#!/bin/sh

# wmctl -i -a 'WINDOW ID'
wmctl -i -a '0x5a00001'

参考文献

How to get window ID from process ID
Is there a linux command to determine the window IDs associated with a given process ID?
How to get an X11 Window from a Process ID?
How to efficiently switch between several terminal windows using the keyboard?
How to switch X windows from the command-line?
wmctrl user documentation