dbus 的一些信息

前言

关于dbus 的一些信息,这个需要了解一下,因为很多的进程通信会用到它。

正文

在我们了解中,操作系统的进程通信有很多,

这些通信都比较的快,比如管道啥的,但是呢?

也有一些问题,那就是不支持复杂的数据结构。

现在我们就总结一下dbus的,优缺点:

优点:标准化、跨语言支持(C/C++、Python、Java 等)、支持复杂数据类型。

缺点:性能不如某些专用 IPC(如共享内存),过度使用可能导致依赖复杂。

那么看下dbus的基本设计是啥?

dbus 分为:

  1. 调用方法
  2. 发送信号
  3. 属性
    他们的区别如下:
    image

调用方法:

dbus-send --session --dest=org.freedesktop.Notifications \
  /org/freedesktop/Notifications org.freedesktop.Notifications.Notify \
  uint32:0 string:"my-icon" string:"Hello" string:"This is a test" array:string:{} dict:string:string:{} int32:5000

那么写在被调用方是:

import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

# 初始化 D-Bus 主循环
DBusGMainLoop(set_as_default=True)

class MyDBusService(dbus.service.Object):
    def __init__(self):
        # 连接到会话总线(Session Bus),并注册服务名
        bus_name = dbus.service.BusName("com.example.MyService", bus=dbus.SessionBus())
        # 指定对象路径
        dbus.service.Object.__init__(self, bus_name, "/com/example/MyService")

    # 定义一个 D-Bus 方法
    @dbus.service.method("com.example.MyInterface",
                         in_signature='s',  # 输入参数类型(s = string)
                         out_signature='s') # 返回值类型
    def SayHello(self, name):
        return f"Hello, {name} from D-Bus!"

# 启动服务
if __name__ == "__main__":
    service = MyDBusService()
    print("D-Bus service is running...")
    # 运行 GLib 事件循环以保持服务活跃
    loop = GLib.MainLoop()
    loop.run()

然后呢,信号其实就是广播:

@dbus.service.signal("com.example.MyInterface", signature='s')
def MySignal(self, message):
    pass  # 信号只需定义,调用时自动发送

最后是属性:

@dbus.service.method("org.freedesktop.DBus.Properties", in_signature='ss', out_signature='v')
def Get(self, interface, prop):
return self._props.get(prop)

D-Bus 属性是专为 状态管理 优化的机制,它:

  1. 提供 统一 的读写接口。

  2. 自动触发 变更通知。

  3. 减少 样板代码。

这里就是属性可以通过调用方法和属性来实现。

介绍一下dbus这个东西,也就是一个系统的软件,一些软件会用到,大致说明一下干什么用的。

posted @ 2025-07-14 18:25  敖毛毛  阅读(21)  评论(0)    收藏  举报