Qt DBus监视器方法调用

Qt DBus Monitor Method Calls

本文关键字:调用 方法 监视器 DBus Qt      更新时间:2023-10-16

我想知道是否有一种简单的方法通过QtDbus来"监视"某个服务的方法调用。例如,我希望当有一个Notify方法调用org.freedesktop.Notifications能够"捕获"它并读取它的参数。

注意*

我可能已经找到了一个解决方案,这是使用Dbus -monitor应用程序,但我想知道是否有更好的方法通过Qt Dbus库。

是的,您应该能够通过QtDBus(做一点工作)做到这一点。基本上,消息总线上的任何客户端都可以订阅任何消息——仅受总线安全策略的限制。(因此,没有办法监视显式不合作的应用程序,除非您对它或消息总线具有调试访问权限。)关键是您将希望在总线本身上使用org.freedesktop.DBus.AddMatch方法:

// first connect our handler object to the QDBusConnection so that it knows what
// to do with the incoming Notify calls
// slotNotifyObserved() must have a compatible signature to the DBus call
QDBusConnection::sessionBus().connect("", // any service name
                                      "", // any object path
                                      "org.freedesktop.Notifications",
                                      "Notify",
                                      myImplementingQObject,
                                      SLOT(slotNotifyObserved(...)));
// then ask the bus to send us a copy of each Notify call message
QString matchString = "interface='org.freedesktop.Notifications',member='Notify',type='method_call',eavesdrop='true'";
QDBusInterface busInterface("org.freedesktop.DBus", "/org/freedesktop/DBus", 
                            "org.freedesktop.DBus");
busInterface.call("AddMatch", matchString);
// once we get back to the event loop our object should be called as other programs
// make Notify() calls

DBus规范给出了matchString中可能出现的各种匹配字段的列表。

为了更好地了解发生了什么,QDBus文档建议设置环境变量QDBUS_DEBUG=1,以使应用程序记录有关其dbus消息传递的信息。