You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 24.04下C++ D-Bus程序无法捕获notify-send通知的问题

问题排查与解决方法

1. 未正确监听org.freedesktop.Notifications接口的Notify方法调用

Notify是**方法调用(method_call)**而非信号(signal),很多开发者会误按信号逻辑来监听。如果你的代码只处理了信号事件,或者监听规则未明确指定type='method_call',就会错过通知。

  • 正确做法:连接会话总线后,添加明确的匹配规则:
    DBusError err;
    dbus_error_init(&err);
    const char* match_rule = "type='method_call',interface='org.freedesktop.Notifications',member='Notify'";
    if (!dbus_bus_add_match(conn, match_rule, &err)) {
        fprintf(stderr, "添加匹配规则失败: %s\n", err.message);
        dbus_error_free(&err);
        return 1;
    }
    dbus_connection_flush(conn);
    

2. 连接的总线类型错误

notify-send的通知发送在**会话总线(session bus)**上,而非系统总线(system bus)。如果代码连接的是系统总线,自然捕获不到事件。

  • 确认连接代码使用会话总线:
    DBusConnection* conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
    

3. 未启动DBus消息循环

注册匹配规则后,必须持续处理消息队列才能接收并解析通知。很多代码遗漏了消息循环逻辑,导致无法获取incoming消息。

  • 基础消息循环示例:
    while (true) {
        dbus_connection_read_write(conn, -1);
        DBusMessage* msg;
        while ((msg = dbus_connection_pop_message(conn)) != nullptr) {
            if (dbus_message_is_method_call(msg, "org.freedesktop.Notifications", "Notify")) {
                // 提取通知内容:标题、正文等
                const char* summary;
                const char* body;
                DBusMessageIter iter;
                dbus_message_iter_init(msg, &iter);
                // 跳过前三个参数(app_name、replaces_id、icon)
                for (int i = 0; i < 3; i++) dbus_message_iter_next(&iter);
                dbus_message_iter_get_basic(&iter, &summary);
                dbus_message_iter_next(&iter);
                dbus_message_iter_get_basic(&iter, &body);
                printf("收到通知:%s - %s\n", summary, body);
            }
            dbus_message_unref(msg);
        }
    }
    

4. 错误请求org.freedesktop.Notifications总线名称

系统默认的通知守护进程已经占用了org.freedesktop.Notifications名称,如果你的代码尝试调用dbus_bus_request_name请求该名称,会导致冲突,进而影响监听逻辑。除非你要替换系统通知服务,否则不要请求这个名称。

5. 权限配置异常(极少情况)

Ubuntu 24.04会话总线默认允许普通用户监听org.freedesktop.Notifications接口,但如果程序以特殊用户运行,可检查/usr/share/dbus-1/session.conf或用户本地DBus配置,确认没有限制相关接口的监听权限。


内容的提问来源于stack exchange,提问作者Venelin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:47:41