60

在 Linux 下,我的 C++ 应用程序使用 fork() 和 execv() 来启动多个 OpenOffice 实例,以便查看一些幻灯片放映。这部分有效。

接下来,我希望能够将 OpenOffice 窗口移动到显示器上的特定位置。我可以使用 XMoveResizeWindow() 函数来做到这一点,但我需要为每个实例找到窗口。

我有每个实例的进程 ID,如何从中找到 X11 窗口?


更新- 感谢安迪的建议,我已经完成了这个。我在此处发布代码以与 Stack Overflow 社区分享。

不幸的是,Open Office 似乎没有设置 _NET_WM_PID 属性,所以这并不能最终解决我的问题,但它确实回答了这个问题。

// Attempt to identify a window by name or attribute.
// by Adam Pierce <adam@doctort.org>

#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <iostream>
#include <list>

using namespace std;

class WindowsMatchingPid
{
public:
    WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid)
        : _display(display)
        , _pid(pid)
    {
    // Get the PID property atom.
        _atomPID = XInternAtom(display, "_NET_WM_PID", True);
        if(_atomPID == None)
        {
            cout << "No such atom" << endl;
            return;
        }

        search(wRoot);
    }

    const list<Window> &result() const { return _result; }

private:
    unsigned long  _pid;
    Atom           _atomPID;
    Display       *_display;
    list<Window>   _result;

    void search(Window w)
    {
    // Get the PID for the current Window.
        Atom           type;
        int            format;
        unsigned long  nItems;
        unsigned long  bytesAfter;
        unsigned char *propPID = 0;
        if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL,
                                         &type, &format, &nItems, &bytesAfter, &propPID))
        {
            if(propPID != 0)
            {
            // If the PID matches, add this window to the result set.
                if(_pid == *((unsigned long *)propPID))
                    _result.push_back(w);

                XFree(propPID);
            }
        }

    // Recurse into child windows.
        Window    wRoot;
        Window    wParent;
        Window   *wChild;
        unsigned  nChildren;
        if(0 != XQueryTree(_display, w, &wRoot, &wParent, &wChild, &nChildren))
        {
            for(unsigned i = 0; i < nChildren; i++)
                search(wChild[i]);
        }
    }
};

int main(int argc, char **argv)
{
    if(argc < 2)
        return 1;

    int pid = atoi(argv[1]);
    cout << "Searching for windows associated with PID " << pid << endl;

// Start with the root window.
    Display *display = XOpenDisplay(0);

    WindowsMatchingPid match(display, XDefaultRootWindow(display), pid);

// Print the result.
    const list<Window> &result = match.result();
    for(list<Window>::const_iterator it = result.begin(); it != result.end(); it++)
        cout << "Window #" << (unsigned long)(*it) << endl;

    return 0;
}
4

8 回答 8

25

我知道这样做的唯一方法是遍历窗口树,直到找到所需的内容。遍历并不难(如果需要示例,只需查看 xwininfo.c 即可了解 xwininfo -root -tree 的作用)。

但是你如何识别你正在寻找的窗口呢? 一些应用程序设置了一个名为 _NET_WM_PID 的窗口属性。

我相信 OpenOffice设置该属性的应用程序之一(就像大多数 Gnome 应用程序一样),所以你很幸运。

于 2008-09-30T02:27:54.990 回答
15

检查 /proc/PID/environ 是否包含名为 WINDOWID 的变量

于 2010-05-02T18:42:26.280 回答
12

派对迟到了。然而:早在 2004 年,Harald Welte 发布了一个代码片段,该代码片段通过 LD_PRELOAD 包装了 XCreateWindow() 调用并将进程 ID 存储在 _NET_WM_PID 中。这确保创建的每个窗口都有一个 PID 条目。

http://www.mail-archive.com/devel@xfree86.org/msg05806.html

于 2012-11-20T21:00:51.637 回答
7

尝试安装xdotool,然后:

#!/bin/bash
# --any and --name present only as a work-around, see: https://github.com/jordansissel/xdotool/issues/14
ids=$(xdotool search --any --pid "$1" --name "dummy")

我确实得到了很多身份证。当使用长命令完成时,我使用它来将终端窗口设置为紧急程序seturgent。我只是遍历所有我从中获得的 idxdotoolseturgent在它们上运行。

于 2014-12-15T14:22:54.493 回答
2

没有什么好办法。我看到的唯一真正的选择是:

  1. 您可以查看进程的地址空间以查找连接信息和窗口 ID。
  2. 您可以尝试使用 netstat 或 lsof 或 ipcs 将连接映射到 Xserver,然后(不知何故!您至少需要 root)查看其连接信息以找到它们。
  3. 当生成一个实例时,你可以等到另一个窗口被映射,假设它是正确的,然后继续。
于 2008-09-30T02:20:57.347 回答
2

我利用一些现代 C++ 特性自由地重新实现了 OP 的代码。它保持相同的功能,但我认为它读起来更好一些。即使向量插入碰巧抛出,它也不会泄漏。

// Attempt to identify a window by name or attribute.
// originally written by Adam Pierce <adam@doctort.org>
// revised by Dario Pellegrini <pellegrini.dario@gmail.com>

#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <iostream>
#include <vector>


std::vector<Window> pid2windows(pid_t pid, Display* display, Window w) {
  struct implementation {
    struct FreeWrapRAII {
      void * data;
      FreeWrapRAII(void * data): data(data) {}
      ~FreeWrapRAII(){ XFree(data); }
    };

    std::vector<Window> result;
    pid_t pid;
    Display* display;
    Atom atomPID;

    implementation(pid_t pid, Display* display): pid(pid), display(display) {
      // Get the PID property atom
      atomPID = XInternAtom(display, "_NET_WM_PID", True);
      if(atomPID == None) {
        throw std::runtime_error("pid2windows: no such atom");
      }
    }

    std::vector<Window> getChildren(Window w) {
      Window    wRoot;
      Window    wParent;
      Window   *wChild;
      unsigned  nChildren;
      std::vector<Window> children;
      if(0 != XQueryTree(display, w, &wRoot, &wParent, &wChild, &nChildren)) {
        FreeWrapRAII tmp( wChild );
        children.insert(children.end(), wChild, wChild+nChildren);
      }
      return children;
    }

    void emplaceIfMatches(Window w) {
      // Get the PID for the given Window
      Atom           type;
      int            format;
      unsigned long  nItems;
      unsigned long  bytesAfter;
      unsigned char *propPID = 0;
      if(Success == XGetWindowProperty(display, w, atomPID, 0, 1, False, XA_CARDINAL,
                                       &type, &format, &nItems, &bytesAfter, &propPID)) {
        if(propPID != 0) {
          FreeWrapRAII tmp( propPID );
          if(pid == *reinterpret_cast<pid_t*>(propPID)) {
            result.emplace_back(w);
          }
        }
      }
    }

    void recurse( Window w) {
      emplaceIfMatches(w);
      for (auto & child: getChildren(w)) {
        recurse(child);
      }
    }

    std::vector<Window> operator()( Window w ) {
      result.clear();
      recurse(w);
      return result;
    }
  };
  //back to pid2windows function
  return implementation{pid, display}(w);
}

std::vector<Window> pid2windows(const size_t pid, Display* display) {
  return pid2windows(pid, display, XDefaultRootWindow(display));
}


int main(int argc, char **argv) {
  if(argc < 2)
    return 1;

  int pid = atoi(argv[1]);
  std::cout << "Searching for windows associated with PID " << pid << std::endl;

  // Start with the root window.
  Display *display = XOpenDisplay(0);
  auto res = pid2windows(pid, display);

  // Print the result.
  for( auto & w: res) {
    std::cout << "Window #" << static_cast<unsigned long>(w) << std::endl;
  }

  XCloseDisplay(display);
  return 0;
}
于 2019-04-30T13:14:39.240 回答
1

你确定你有每个实例的进程 ID 吗?我对 OOo 的经验是,尝试运行 OOo 的第二个实例只是与 OOo 的第一个实例对话,并告诉它打开附加文件。

我认为您将需要使用 X 的消息发送功能来很好地询问它的窗口。我希望 OOo 在某处记录其覆盖范围。

于 2008-09-30T02:13:55.430 回答
0

如果你使用 python,我在这里找到了一个方法,这个想法来自BurntSushi

如果您启动了应用程序,那么您应该知道它的 cmd 字符串,使用它可以减少对 的调用xprop,您可以随时循环遍历所有 xid 并检查 pid 是否与您想要的 pid 相同

import subprocess
import re

import struct
import xcffib as xcb
import xcffib.xproto

def get_property_value(property_reply):
    assert isinstance(property_reply, xcb.xproto.GetPropertyReply)

    if property_reply.format == 8:
        if 0 in property_reply.value:
            ret = []
            s = ''
            for o in property_reply.value:
                if o == 0:
                    ret.append(s)
                    s = ''
                else:
                    s += chr(o)
        else:
            ret = str(property_reply.value.buf())

        return ret
    elif property_reply.format in (16, 32):
        return list(struct.unpack('I' * property_reply.value_len,
                                  property_reply.value.buf()))

    return None

def getProperty(connection, ident, propertyName):

    propertyType = eval(' xcb.xproto.Atom.%s' % propertyName)

    try:
        return connection.core.GetProperty(False, ident, propertyType,
                                        xcb.xproto.GetPropertyType.Any,
                                        0, 2 ** 32 - 1)
    except:
        return None


c = xcb.connect()
root = c.get_setup().roots[0].root

_NET_CLIENT_LIST = c.core.InternAtom(True, len('_NET_CLIENT_LIST'),
                                     '_NET_CLIENT_LIST').reply().atom


raw_clientlist = c.core.GetProperty(False, root, _NET_CLIENT_LIST,
                                    xcb.xproto.GetPropertyType.Any,
                                    0, 2 ** 32 - 1).reply()

clientlist = get_property_value(raw_clientlist)

cookies = {}

for ident in clientlist:
    wm_command = getProperty(c, ident, 'WM_COMMAND')
    cookies[ident] = (wm_command)

xids=[]

for ident in cookies:
    cmd = get_property_value(cookies[ident].reply())
    if cmd and spref in cmd:
        xids.append(ident)

for xid in xids:
    pid = subprocess.check_output('xprop -id %s _NET_WM_PID' % xid, shell=True)
    pid = re.search('(?<=\s=\s)\d+', pid).group()

    if int(pid) == self.pid:
        print 'found pid:', pid
        break

print 'your xid:', xid
于 2017-04-23T00:33:55.077 回答