dbus介绍与例子

2024-04-30 09:18
文章标签 介绍 例子 dbus

本文主要是介绍dbus介绍与例子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  D-bus是一个进程间通信的工具,优点不在这里赘述。


  网上很多关于dbus的帖子都是基于dbus-glib或者QT D-bus的,直接使用dbus的教程比较少。也难怪,因为连D-bus的官网都说:"If you use this low-level API directly, you're signing up for some pain."

  但实际上,直接使用D-bus也没有想象中难。本文将对直接使用D-bus做一个介绍。


本文参考了其他一些网站的帖子或者介绍

官网:http://www.freedesktop.org/wiki/Software/dbus/

经典例子:http://www.matthew.ath.cx/articles/dbus

不错的帖子:http://blog.csdn.net/flowingflying/article/details/4527634


一、概念介绍

  这里虽然说是概念介绍,其实只是我个人对D-bus的一个理解,不一定完整准确。

 1.首先,D-bus可以分成三部分来看,

(1)dbus-daemon,一个dbus的后台守护程序,用于多个应用之间消息的转发;

(2)libdbus.so,dbus的功能接口,当你的程序需要使用dbus时,其实就是调用libdbus.so里面的接口;

(3)高层封装,如dbus-glib和QT D-bus,这些其实都对D-bus的再封装,让你使用起来更方便。

  从D-bus官网下载到源码,其实只包含上面所说的1和2两部分,libdbus.so里面的接口也就是官网说的low-level API。


2.关于address、bus name、path。。。。

  D-bus里面提到了一些概念,刚开始不太好理解,这些概念也很容易混淆。这些概念的权威解释可以看这里。

  首先,运行一个dbus-daemon就是创建了一条通信的总线Bus。当一个application连接到这条Bus上面时,就产生了Connection。

  每个application里面会有不同的Object。这里Object的概念,可以简单地理解为C++里面一个类的实例。从D-bus的概念上说,通信双方是Object,不是application,一个application是可以包含很多个Object的。

  而一个Object里面又会有不同的Interface,这个Interface我把它理解为Object里面的一个类的成员。这些Interface其实是通信方式的集合。

  这里又牵扯出来一个通信方式,D-bus里面支持的通信方式有两种,一种叫signal,一种叫method。signal简单地讲,其实就是广播,就是一对多的通信方式,可以从app1向其他所有的app发消息,但其他的app是不会对signal进行回复的。method则是一对一的通信,一问一答。这种方式有点像远程调用,app1调用app2的method并传递参数给这个method,获取到这个method返回的结果。

  上面把D-bus通信里面的几个重要元素都介绍了一下,大概的关系是这样的:


  几个重要的元素之间的关系都画出来了,那么在程序里面怎么去标识这些元素呢?这里又提出来了一些名词address、bus name、path、Interface name。

(1)address是用来标识dbus-daemon的。当一个dbus-daemon运行以后,其他的app该怎么连接到这个dbus-daemon,靠的就是address。address的格式要求像这样:unix:path=/var/run/dbus/system_bus_socket

(2)bus name是用来标识application的。当一个app1连接上dbus-daemon以后,相当于有了一个Connection,但其他的app2、app3怎么找到app1,靠的就是bus name。这个bus name标识了app1的Connection,也就相当于标识了app1。bus name由两种,一种是已冒号开头的唯一标识,像:34-907这样;另一种是通用的标识,是方便人看的,像com.mycompany.TextEditor

(3)path用于标识Object。当app1的Object1要跟app2的Object2通信时,Object1要和Object2通信时,就要告诉dbus-daemon,Object2的path。path的格式像这样,/com/mycompany/TextFileManager,已“/”开头。

(4)每个Interface都会有自己的名字,也就是interface name,我们通过这个interface name就可以找到这个interface。interface name像这样org.freedesktop.Hal.Manager

(5)Signal和Method也有自己的名字,这个名字没什么特别的格式要求,随便改个名字就可以了。

  官网上对这些标识列了一个表,如下:

A...is identified by a(n)...which looks like...and is chosen by...
Busaddressunix:path=/var/run/dbus/system_bus_socketsystem configuration
Connectionbus name:34-907 (unique) or com.mycompany.TextEditor (well-known)D-Bus (unique) or the owning program (well-known)
Objectpath/com/mycompany/TextFileManagerthe owning program
Interfaceinterface nameorg.freedesktop.Hal.Managerthe owning program
Membermember nameListNamesthe owning program

二、例子

我在Matthew Johnson和恺风的例子基础上做了修改,如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dbus/dbus.h>/** listen, wait a call or a signal*/
#define DBUS_SENDER_BUS_NAME        "com.ty3219.sender_app"#define DBUS_RECEIVER_BUS_NAME      "com.ty3219.receiver_app"
#define DBUS_RECEIVER_PATH          "/com/ty3219/object"
#define DBUS_RECEIVER_INTERFACE     "com.ty3219.interface"
#define DBUS_RECEIVER_SIGNAL        "signal"
#define DBUS_RECEIVER_METHOD        "method"#define DBUS_RECEIVER_SIGNAL_RULE   "type='signal',interface='%s'"
#define DBUS_RECEIVER_REPLY_STR     "i am %d, get a message"#define MODE_SIGNAL                 1
#define MODE_METHOD                 2#define DBUS_CLIENT_PID_FILE        "/tmp/dbus-client.pid"/**** @param msg* @param conn*/
void reply_method_call(DBusMessage *msg, DBusConnection *conn)
{DBusMessage *reply;DBusMessageIter reply_arg;DBusMessageIter msg_arg;dbus_uint32_t serial = 0;pid_t pid;char reply_str[128];void *__value;char *__value_str;int __value_int;int ret;pid = getpid();//创建返回消息replyreply = dbus_message_new_method_return(msg);if (!reply){printf("Out of Memory!\n");return;}//在返回消息中填入参数。snprintf(reply_str, sizeof(reply_str), DBUS_RECEIVER_REPLY_STR, pid);__value_str = reply_str;__value = &__value_str;dbus_message_iter_init_append(reply, &reply_arg);if (!dbus_message_iter_append_basic(&reply_arg, DBUS_TYPE_STRING, __value)){printf("Out of Memory!\n");goto out;}//从msg中读取参数,根据传入参数增加返回参数if (!dbus_message_iter_init(msg, &msg_arg)){printf("Message has NO Argument\n");goto out;}do{int ret = dbus_message_iter_get_arg_type(&msg_arg);if (DBUS_TYPE_STRING == ret){dbus_message_iter_get_basic(&msg_arg, &__value_str);printf("I am %d, get Method Argument STRING: %s\n", pid,__value_str);__value = &__value_str;if (!dbus_message_iter_append_basic(&reply_arg,DBUS_TYPE_STRING, __value)){printf("Out of Memory!\n");goto out;}}else if (DBUS_TYPE_INT32 == ret){dbus_message_iter_get_basic(&msg_arg, &__value_int);printf("I am %d, get Method Argument INT32: %d\n", pid,__value_int);__value_int++;__value = &__value_int;if (!dbus_message_iter_append_basic(&reply_arg,DBUS_TYPE_INT32, __value)){printf("Out of Memory!\n");goto out;}}else{printf("Argument Type ERROR\n");}} while (dbus_message_iter_next(&msg_arg));//发送返回消息if (!dbus_connection_send(conn, reply, &serial)){printf("Out of Memory\n");goto out;}dbus_connection_flush(conn);
out:dbus_message_unref(reply);
}/* 监听D-Bus消息,我们在上次的例子中进行修改 */
void dbus_receive(void)
{DBusMessage *msg;DBusMessageIter arg;DBusConnection *connection;DBusError err;pid_t pid;char name[64];char rule[128];const char *path;void *__value;char *__value_str;int __value_int;int ret;pid = getpid();dbus_error_init(&err);//创建于session D-Bus的连接connection = dbus_bus_get(DBUS_BUS_SESSION, &err);if (!connection){if (dbus_error_is_set(&err))printf("Connection Error %s\n", err.message);goto out;}//设置一个BUS nameif (0 == access(DBUS_CLIENT_PID_FILE, F_OK))snprintf(name, sizeof(name), "%s%d", DBUS_RECEIVER_BUS_NAME, pid);elsesnprintf(name, sizeof(name), "%s", DBUS_RECEIVER_BUS_NAME);printf("i am a receiver, PID = %d, name = %s\n", pid, name);ret = dbus_bus_request_name(connection, name,DBUS_NAME_FLAG_REPLACE_EXISTING, &err);if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER){if (dbus_error_is_set(&err))printf("Name Error %s\n", err.message);goto out;}//要求监听某个signal:来自接口test.signal.Type的信号snprintf(rule, sizeof(rule), DBUS_RECEIVER_SIGNAL_RULE, DBUS_RECEIVER_INTERFACE);dbus_bus_add_match(connection, rule, &err);dbus_connection_flush(connection);if (dbus_error_is_set(&err)){printf("Match Error %s\n", err.message);goto out;}while (1){dbus_connection_read_write(connection, 0);msg = dbus_connection_pop_message(connection);if (msg == NULL){sleep(1);continue;}path = dbus_message_get_path(msg);if (strcmp(path, DBUS_RECEIVER_PATH)){printf("Wrong PATH: %s\n", path);goto next;}printf("Get a Message\n");if (dbus_message_is_signal(msg, DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_SIGNAL)){printf("Someone Send me a Signal\n");if (!dbus_message_iter_init(msg, &arg)){printf("Message Has no Argument\n");goto next;}ret = dbus_message_iter_get_arg_type(&arg);if (DBUS_TYPE_STRING == ret){dbus_message_iter_get_basic(&arg, &__value_str);printf("I am %d, Got Signal with STRING: %s\n",pid, __value_str);}else if (DBUS_TYPE_INT32 == ret){dbus_message_iter_get_basic(&arg, &__value_int);printf("I am %d, Got Signal with INT32: %d\n",pid, __value_int);}else{printf("Argument Type ERROR\n");goto next;}}else if (dbus_message_is_method_call(msg, DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_METHOD)){printf("Someone Call My Method\n");reply_method_call(msg, connection);}else{printf("NOT a Signal OR a Method\n");}
next:dbus_message_unref(msg);}out:dbus_error_free(&err);
}/** call a method*/
static void dbus_send(int mode, char *type, void *value)
{DBusConnection *connection;DBusError err;DBusMessage *msg;DBusMessageIter arg;DBusPendingCall *pending;dbus_uint32_t serial;int __type;void *__value;char *__value_str;int __value_int;pid_t pid;int ret;pid = getpid();//Step 1: connecting session bus/* initialise the erroes */dbus_error_init(&err);/* Connect to Bus*/connection = dbus_bus_get(DBUS_BUS_SESSION, &err);if (!connection){if (dbus_error_is_set(&err))printf("Connection Err : %s\n", err.message);goto out1;}//step 2: 设置BUS name,也即连接的名字。ret = dbus_bus_request_name(connection, DBUS_SENDER_BUS_NAME,DBUS_NAME_FLAG_REPLACE_EXISTING, &err);if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER){if (dbus_error_is_set(&err))printf("Name Err : %s\n", err.message);goto out1;}if (!strcasecmp(type, "STRING")){__type = DBUS_TYPE_STRING;__value_str = value;__value = &__value_str;}else if (!strcasecmp(type, "INT32")){__type = DBUS_TYPE_INT32;__value_int = atoi(value);__value = &__value_int;}else{printf("Wrong Argument Type\n");goto out1;}if (mode == MODE_METHOD){printf("Call app[bus_name]=%s, object[path]=%s, interface=%s, method=%s\n",DBUS_RECEIVER_BUS_NAME, DBUS_RECEIVER_PATH,DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_METHOD);//针对目的地地址,创建一个method call消息。//Constructs a new message to invoke a method on a remote object.msg = dbus_message_new_method_call(DBUS_RECEIVER_BUS_NAME, DBUS_RECEIVER_PATH,DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_METHOD);if (msg == NULL){printf("Message NULL");goto out1;}dbus_message_iter_init_append(msg, &arg);if (!dbus_message_iter_append_basic(&arg, __type, __value)){printf("Out of Memory!");goto out2;}//发送消息并获得reply的handle 。Queues a message to send, as with dbus_connection_send() , but also returns a DBusPendingCall used to receive a reply to the message.if (!dbus_connection_send_with_reply(connection, msg, &pending, -1)){printf("Out of Memory!");goto out2;}if (pending == NULL){printf("Pending Call NULL: connection is disconnected ");goto out2;}dbus_connection_flush(connection);dbus_message_unref(msg);//waiting a reply,在发送的时候,已经获取了method reply的handle,类型为DBusPendingCall。// block until we receive a reply, Block until the pending call is completed.dbus_pending_call_block(pending);// get the reply message,Gets the reply, or returns NULL if none has been received yet.msg = dbus_pending_call_steal_reply(pending);if (msg == NULL){printf("Reply Null\n");goto out1;}// free the pending message handledbus_pending_call_unref(pending);// read the Argumentsif (!dbus_message_iter_init(msg, &arg)){printf("Message has no Argument!\n");goto out2;}do{int ret = dbus_message_iter_get_arg_type(&arg);if (DBUS_TYPE_STRING == ret){dbus_message_iter_get_basic(&arg, &__value_str);printf("I am %d, get Method return STRING: %s\n", pid,__value_str);}else if (DBUS_TYPE_INT32 == ret){dbus_message_iter_get_basic(&arg, &__value_int);printf("I am %d, get Method return INT32: %d\n", pid,__value_int);}else{printf("Argument Type ERROR\n");}} while (dbus_message_iter_next(&arg));printf("NO More Argument\n");}else if (mode == MODE_SIGNAL){printf("Signal to object[path]=%s, interface=%s, signal=%s\n",DBUS_RECEIVER_PATH, DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_SIGNAL);//步骤3:发送一个信号//根据图,我们给出这个信号的路径(即可以指向对象),接口,以及信号名,创建一个Messagemsg = dbus_message_new_signal(DBUS_RECEIVER_PATH,DBUS_RECEIVER_INTERFACE, DBUS_RECEIVER_SIGNAL);if (!msg){printf("Message NULL\n");goto out1;}dbus_message_iter_init_append(msg, &arg);if (!dbus_message_iter_append_basic(&arg, __type, __value)){printf("Out of Memory!");goto out2;}//将信号从连接中发送if (!dbus_connection_send(connection, msg, &serial)){printf("Out of Memory!\n");goto out2;}dbus_connection_flush(connection);printf("Signal Send\n");}out2:dbus_message_unref(msg);
out1:dbus_error_free(&err);
}static void usage(void)
{
#define USAGE "usage: ./dbus-client [send | receive] <param>\n" \"\treceive -- listen, wait a signal or a method call\n" \"\t\tif you want to test signal broadcast, run two receiver like this:\n" \"\t\trm -f /tmp/dbus-client.pid\n" \"\t\t./dbus-client receive &\n" \"\t\techo > /tmp/dbus-client.pid\n" \"\t\t./dbus-client receive &\n" \"\tsend [mode] [type] [value] -- send a signal or call a method\n" \"\t\tmode -- SIGNAL | METHOD\n" \"\t\ttype -- STRING | INT32\n" \"\t\tvalue -- string or number\n" \"\t\texample:\n" \"\t\t./dbus-client send SIGNAL STRING hello\n" \"\t\t./dbus-client send METHOD INT32 99\n" \"\n"printf(USAGE);
}int main(int argc, char *argv[])
{if (argc < 2){usage();return -1;}if (!strcmp(argv[1], "receive")){dbus_receive();}else if (!strcmp(argv[1], "send")){if (argc < 5){usage();}else{if (!strcasecmp(argv[2], "SIGNAL"))dbus_send(MODE_SIGNAL, argv[3], argv[4]);else if (!strcasecmp(argv[2], "METHOD"))dbus_send(MODE_METHOD, argv[3], argv[4]);elseusage();}}else{usage();}return 0;
}

三、运行

  想要运行上面的例子,还需要一些步骤。

(1)运行dbus-daemon

dbus-daemon的运行需要一个配置文件,这个配置文件稍微有点复杂,这里提供一个最简单的,无任何权限检查的例子debug-allow-all.conf

<!-- Bus that listens on a debug pipe and doesn't create any restrictions --><!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN""http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig><type>session</type><listen>unix:tmpdir=/tmp</listen><standard_session_servicedirs /><policy context="default"><!-- Allow everything to be sent --><allow send_destination="*" eavesdrop="true"/><!-- Allow everything to be received --><allow eavesdrop="true"/><!-- Allow anyone to own anything --><allow own="*"/><allow user="*"/></policy></busconfig>
  

执行下面的命令

./dbus-daemon --config-file=/path/to/debug-allow-all.conf --fork --print-address
此时,dbus-daemon就会打印出一句类似这样的话

unix:path=/tmp/dbus-UXeqD3TJHE,guid=88e7712c8a5775ab4599725500000051

其实这个就是dbus-daemon的地址,我们需要把这个地址设置到环境变量里面,当你运行app的时候,libdbus.so就会读取这个环境变量,然后连接到这个dbus-daemon上。

设置环境变量

export DBUS_SESSION_BUS_ADDRESS=unix:path=/tmp/dbus-UXeqD3TJHE,guid=88e7712c8a5775ab4599725500000051

(2)这个时候你就可以运行上面例子编译出来的程序

./dbus-app
此时,会打印出一些参数信息。这个例子程序其实既可收也可以发,

作为接收方时运行

./dbus-app receive &
可以运行多个dbus-app作为接收方,这样测试signal时就可以看到多个dbus-app同时受到这个signal了。

作为发送方时,发送signal


./dbus-app send SIGNAL STRING hello

作为发送方时,调用method

/dbus-app send METHOD INT32 30

  至此,一个dbus的例子就可以运行起来了,想详细了解这个例子需要自己去看例子的源码。


这篇关于dbus介绍与例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/948473

相关文章

性能测试介绍

性能测试是一种测试方法,旨在评估系统、应用程序或组件在现实场景中的性能表现和可靠性。它通常用于衡量系统在不同负载条件下的响应时间、吞吐量、资源利用率、稳定性和可扩展性等关键指标。 为什么要进行性能测试 通过性能测试,可以确定系统是否能够满足预期的性能要求,找出性能瓶颈和潜在的问题,并进行优化和调整。 发现性能瓶颈:性能测试可以帮助发现系统的性能瓶颈,即系统在高负载或高并发情况下可能出现的问题

水位雨量在线监测系统概述及应用介绍

在当今社会,随着科技的飞速发展,各种智能监测系统已成为保障公共安全、促进资源管理和环境保护的重要工具。其中,水位雨量在线监测系统作为自然灾害预警、水资源管理及水利工程运行的关键技术,其重要性不言而喻。 一、水位雨量在线监测系统的基本原理 水位雨量在线监测系统主要由数据采集单元、数据传输网络、数据处理中心及用户终端四大部分构成,形成了一个完整的闭环系统。 数据采集单元:这是系统的“眼睛”,

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

图神经网络模型介绍(1)

我们将图神经网络分为基于谱域的模型和基于空域的模型,并按照发展顺序详解每个类别中的重要模型。 1.1基于谱域的图神经网络         谱域上的图卷积在图学习迈向深度学习的发展历程中起到了关键的作用。本节主要介绍三个具有代表性的谱域图神经网络:谱图卷积网络、切比雪夫网络和图卷积网络。 (1)谱图卷积网络 卷积定理:函数卷积的傅里叶变换是函数傅里叶变换的乘积,即F{f*g}

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现

Mysql BLOB类型介绍

BLOB类型的字段用于存储二进制数据 在MySQL中,BLOB类型,包括:TinyBlob、Blob、MediumBlob、LongBlob,这几个类型之间的唯一区别是在存储的大小不同。 TinyBlob 最大 255 Blob 最大 65K MediumBlob 最大 16M LongBlob 最大 4G

FreeRTOS-基本介绍和移植STM32

FreeRTOS-基本介绍和STM32移植 一、裸机开发和操作系统开发介绍二、任务调度和任务状态介绍2.1 任务调度2.1.1 抢占式调度2.1.2 时间片调度 2.2 任务状态 三、FreeRTOS源码和移植STM323.1 FreeRTOS源码3.2 FreeRTOS移植STM323.2.1 代码移植3.2.2 时钟中断配置 一、裸机开发和操作系统开发介绍 裸机:前后台系

nginx介绍及常用功能

什么是nginx nginx跟Apache一样,是一个web服务器(网站服务器),通过HTTP协议提供各种网络服务。 Apache:重量级的,不支持高并发的服务器。在Apache上运行数以万计的并发访问,会导致服务器消耗大量内存。操作系统对其进行进程或线程间的切换也消耗了大量的CPU资源,导致HTTP请求的平均响应速度降低。这些都决定了Apache不可能成为高性能WEB服务器  nginx:

多路转接之select(fd_set介绍,参数详细介绍),实现非阻塞式网络通信

目录 多路转接之select 引入 介绍 fd_set 函数原型 nfds readfds / writefds / exceptfds readfds  总结  fd_set操作接口  timeout timevalue 结构体 传入值 返回值 代码 注意点 -- 调用函数 select的参数填充  获取新连接 注意点 -- 通信时的调用函数 添加新fd到

火语言RPA流程组件介绍--浏览网页

🚩【组件功能】:浏览器打开指定网址或本地html文件 配置预览 配置说明 网址URL 支持T或# 默认FLOW输入项 输入需要打开的网址URL 超时时间 支持T或# 打开网页超时时间 执行后后等待时间(ms) 支持T或# 当前组件执行完成后继续等待的时间 UserAgent 支持T或# User Agent中文名为用户代理,简称 UA,它是一个特殊字符串头,使得服务器