问题描述
当我们发现某个进程占用资源(比如 CPU、内存等等)非常多时,我们需要确定是哪个应用导致的。
如何才能快速找到对应的窗口呢?在多数情况下,直接查看进程正在执行的命令,就能找到对应的窗口。
但是,某些情况下,例如,同个程序运行多个实例(例如,打开多个浏览器实例),怎样才能确定是哪一个占用资源呢?
该笔记将介绍:在桌面环境下,X11,如何通过进程 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"
xprop -id $id
fi
fi
done
EOF
# 找到窗口的 ID 值,形如「0x5a00001」格式。
sh /tmp/find-window.sh "<PID>"
#3 切换到该窗口
使用 wmctrl 可以切换到该窗口,但前提是「窗口管理器」要符合 EWMH 标准:
#!/bin/sh # wmctrl -i -a 'WINDOW ID' wmctrl -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?