一种IPC通信机制Gdbus详解

2023-10-27 22:10

本文主要是介绍一种IPC通信机制Gdbus详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、DBus介绍

常规进程间通信有管道,消息队列,共享内存,以及socket等,每个都有优劣,这次我们介绍一种高阶的进程间通信方式DBus。
DBus通信是IPC通信机制的一种方式,本身是建立在socket机制之上,它支持远程函数调用和信号传递。
它有两种模式,分别为:session(会话模式)、system(总线模式)
总线模式(system bus):采用总线模式时,系统需要维护一个DBus Daemon,每个DBus的请求通过DBus Daemon转发。这种模式Server只需要维护一个与DBus Daemon的链接,结构清晰,可以通过广播的方式发送消息到各个Client。
会话模式(session bus):这种模式一般称之为点对点的星型结构,Client与Server之间是直接的Peer2Peer的连接,少了DBus Daemon的中转,因此性能较好。
在这里插入图片描述

二、DBus API

glib API中有两种可以用的,分别是dbus-glib和gdbus,dbus-glib是一种老的API,现在不推荐使用了,gdbus是从glib2.26开始添加的,目前推荐使用。gdbus和glib-dbus都是GNU组织开发的,gdbus可以认为是dbus-glib的升级版,其编程过程比起dbus-glib来要简单得多。

三、DBus 开发

多进程之间需要通信,可能有一对一,可能有一对多,多对多的通信方式。为简单起见,我们假设某个系统中就只有两个进程需要通信——我们称之为Server和Client。基于GDBus的进程间通信,首先就是要定义好Server和Client之间的通信接口。在GDBus编程框架下,我们使用xml文件来描述接口,然后通过GDbus提供的工具生成对应的C/C++代码。
通常应用的组织形式如下,服务端发布的时候同时提供接口库供其他客户端程序调用,客户端连接接口库即可,像正常的接口调用,如下图,下面我们通过一个设置、获取一个人姓名和年龄,并且设置完姓名和年龄后会广播给所有客户端的程序来学习一下GDBus。
在这里插入图片描述
interface_people.xml

<?xml version="1.0" encoding="UTF-8"?>
<node><interface name="gdbus.demo.people"><method name="set_name"><arg name="name" type="s" direction="in"/><arg name="ret" type="b" direction="out"/></method><method name="get_name"><arg name="name" type="s" direction="out"/></method><method name="set_age"><arg name="age" type="i" direction="in"/><arg name="ret" type="b" direction="out"/></method><method name="get_age"><arg name="age" type="i" direction="out"/></method><signal name="send_info"><arg name="name" type="s"/><arg name="age" type="i"/></signal></interface>
</node>

四、数据类型介绍

上面XML中使用了一些数据类型,对应关系如下表。
1、基本数据类型

NameCode in D-BusData Type in glibData Type in libdbus-C++
BYTE‘y’gucharunsigned char
BOOLEAN‘b’gbooleanbool
INT16‘n’gint16signed short
UINT16‘q’guint16unsigned short
INT32‘i’gintint
UINT32‘u’guintunsigned int
INT64‘x’gint64signed long long
UINT64‘t’guint64unsigned long long
DOUBLE‘d’gdoubledouble
STRING‘s’const gchar *std::string
OBJECT_PATH‘o’const gchar *DBus::Path :public std::string
UNIX_FD‘h’GVariant *int
SIGNATURE‘g’const gchar *DBus::Signature :public std::string

2、复杂数据类型

NameCode in D-BusData Type in glibData Type in libdbus-C++
STRUCT‘(‘ and ‘)’GvariantDBus::Struct<>
ARRAY‘a’Gvariantstd::vector<>
VARIANT‘v’GvariantDBus::Variant
DICT_ENTRY‘{’ and ‘}’(Only appear after ‘a’)GvariantWhen it is used together with ‘a’,it is representedby std::map<>

五、程序运行

gdbus运行需要先运行deamon和环境变量
方法一:
1、运行下面脚本,生成地址,同时这个daemon要跑着

dbus-daemon --config-file=/etc/dbus-1/session.conf --print-address

2、生成的地址替换掉下面的地址部分

export DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-4z6nMwqewd,guid=e6359f4ef81d07fc7185fb8b6059d267

3、在需要运行程序的终端中设置上面的环境变量
方法二:
1、执行完下面脚本,然后在同一终端运行Server和Client

eval dbus-launch --auto-syntax

方法三:

export DBUS_SESSION_BUS_ADDRESS="unix:abstract=/tmp/dbus-cwrMdqoyqU,guid=4780330fcb5755ab1492ce8800000024"
dbus-daemon --config-file=/etc/dbus-1/session.conf --address=$DBUS_SESSION_BUS_ADDRESS

六、代码附录

文件结构如下
在这里插入图片描述
重点代码
client.cpp

#include <iostream>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>#include "interface.h"using namespace std;int main(void)
{string name = "";int age = 0;interface iface;iface.initDBusCommunication();name = "dongdong.fan";iface.set_name(name);iface.set_age(30);name = iface.get_name();age = iface.get_age();cout << "Have a people name:" << name << "age:" << age;while (1){sleep(10);}return 0;
}

service.cpp

#include <unistd.h>#include "people.h"
#include "gdbusServer.h"int main()
{initDBusCommunication();while (1){sleep(10);}return 0;
}

gdbusServer.cpp

#include "gdbusServer.h"#include <ctype.h>
#include <gio/gio.h>
#include <glib.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>#include "gdbusCommon.h"
#include "people.h"
#include "people_gen_interface.h"static guint g_own_id = 0;
static GMainLoop *g_pLoop = NULL;
static GdbusDemoPeople *g_pSkeleton = NULL;
static people g_people;// start
static gboolean set_name_method(GdbusDemoPeople *object,GDBusMethodInvocation *invocation,const gchar *in_arg,gpointer user_data) {my_printf("Server set_name_method is call, arg is : %s.\n", in_arg);bool ret = 0;string strTemp = in_arg;ret = g_people.set_name(strTemp);gdbus_demo_people_complete_set_name(object, invocation, ret);// 同时广播gdbus_demo_people_emit_send_info(object,g_people.get_name().c_str(),g_people.get_age());return TRUE;
}static gboolean get_name_method(GdbusDemoPeople *object,GDBusMethodInvocation *invocation,const gchar *in_arg,gpointer user_data) {my_printf("Server get_name_method is call.\n");string strTemp = g_people.get_name();gdbus_demo_people_complete_get_name(object, invocation, strTemp.c_str());return TRUE;
}static gboolean set_age_method(GdbusDemoPeople *object,GDBusMethodInvocation *invocation,gint in_arg,gpointer user_data) {my_printf("Server set_age_method is call, arg is : %d.\n", in_arg);bool ret = 0;ret = g_people.set_age(in_arg);gdbus_demo_people_complete_set_age(object, invocation, ret);// 同时广播gdbus_demo_people_emit_send_info(object,g_people.get_name().c_str(),g_people.get_age());return TRUE;
}static gboolean get_age_method(GdbusDemoPeople *object,GDBusMethodInvocation *invocation,gpointer user_data) {my_printf("Server get_age_method is call.\n");int age = g_people.get_age();gdbus_demo_people_complete_get_age(object, invocation, age);return TRUE;
}
// endstatic void GBusAcquired_Callback(GDBusConnection *connection,const gchar *name,gpointer user_data) {GError *pError = NULL;g_pSkeleton = gdbus_demo_people_skeleton_new();// Attach to dbus signals// start(void)g_signal_connect(g_pSkeleton, "handle-set-name", G_CALLBACK(set_name_method), NULL);(void)g_signal_connect(g_pSkeleton, "handle-get-name", G_CALLBACK(get_name_method), NULL);(void)g_signal_connect(g_pSkeleton, "handle-set-age", G_CALLBACK(set_age_method), NULL);(void)g_signal_connect(g_pSkeleton, "handle-get-age", G_CALLBACK(get_age_method), NULL);// end(void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(g_pSkeleton),connection,GDBUS_DEMO_PEOPLE_OBJECT_PATH,&pError);if (pError == 0) {my_printf("skeleton export successfully. \n");} else {my_printf("Error: Failed to export object. Reason: %s.\n", pError->message);g_error_free(pError);g_main_loop_quit(g_pLoop);return;}
}static void GBusNameAcquired_Callback(GDBusConnection *connection,const gchar *name,gpointer user_data) {my_printf("GBusNameAcquired_Callback, Acquired bus name: %s \n", GDBUS_DEMO_PEOPLE_NAME);
}static void GBusNameLost_Callback(GDBusConnection *connection,const gchar *name,gpointer user_data) {if (connection == NULL) {my_printf("GBusNameLost_Callback, Error: Failed to connect to dbus. \n");} else {my_printf("GBusNameLost_Callback, Error: Failed to get dbus name : %s\n", GDBUS_DEMO_PEOPLE_NAME);}g_main_loop_quit(g_pLoop);
}static void *run_callback(void *arg) {g_main_loop_run(g_pLoop);return NULL;
}bool initDBusCommunication(void) {bool ret = false;pthread_t tid;g_pLoop = g_main_loop_new(NULL, FALSE);if (NULL == g_pLoop) {my_printf("g_pLoop is NULL\n");goto LEAVE;}g_own_id = g_bus_own_name(G_BUS_TYPE_SESSION,GDBUS_DEMO_PEOPLE_NAME,G_BUS_NAME_OWNER_FLAGS_NONE,&GBusAcquired_Callback,&GBusNameAcquired_Callback,&GBusNameLost_Callback,NULL,NULL);pthread_create(&tid, NULL, run_callback, NULL);ret = true;
LEAVE:return ret;
}bool uinitDBusCommunication(void) {g_bus_unown_name(g_own_id);g_main_loop_unref(g_pLoop);return true;
}

gdbusServer.cpp

#ifndef _GDBUS_SERVER_H_
#define _GDBUS_SERVER_H_bool initDBusCommunication(void);
bool uinitDBusCommunication(void);#endif

people.cpp

#include "people.h"people::people()
{m_name = "default";m_age = 20;
}people::~people()
{//todo
}bool people::set_name(string &name)
{m_name = name;return true;
}string people::get_name()
{return m_name;
}bool people::set_age(int age)
{m_age = age;return true;
}int people::get_age()
{return m_age;
}

people.hpp

#ifndef _PEOPLE_H_
#define _PEOPLE_H_#include <string>using namespace std;class people
{public:people();~people();bool set_name(string &name);string get_name();bool set_age(int age);int get_age();private:string m_name;     // 姓名int m_age;         // 年龄  
};#endif

interface.hpp

#ifndef  _INTERFACE_H_
#define  _INTERFACE_H_#include <string>class interface
{public:interface();virtual ~interface();bool initDBusCommunication(void);//peoplebool set_name(std::string &name);std::string get_name();bool set_age(int age);int get_age();
};#endif

这篇关于一种IPC通信机制Gdbus详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python基础文件操作方法超详细讲解(详解版)

《Python基础文件操作方法超详细讲解(详解版)》文件就是操作系统为用户或应用程序提供的一个读写硬盘的虚拟单位,文件的核心操作就是读和写,:本文主要介绍Python基础文件操作方法超详细讲解的相... 目录一、文件操作1. 文件打开与关闭1.1 打开文件1.2 关闭文件2. 访问模式及说明二、文件读写1.

详解C++中类的大小决定因数

《详解C++中类的大小决定因数》类的大小受多个因素影响,主要包括成员变量、对齐方式、继承关系、虚函数表等,下面就来介绍一下,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 非静态数据成员示例:2. 数据对齐(Padding)示例:3. 虚函数(vtable 指针)示例:4. 继承普通继承虚继承5.

前端高级CSS用法示例详解

《前端高级CSS用法示例详解》在前端开发中,CSS(层叠样式表)不仅是用来控制网页的外观和布局,更是实现复杂交互和动态效果的关键技术之一,随着前端技术的不断发展,CSS的用法也日益丰富和高级,本文将深... 前端高级css用法在前端开发中,CSS(层叠样式表)不仅是用来控制网页的外观和布局,更是实现复杂交

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

详解C#如何提取PDF文档中的图片

《详解C#如何提取PDF文档中的图片》提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使用,下面我们就来看看如何使用C#通过代码从PDF文档中提取图片吧... 当 PDF 文件中包含有价值的图片,如艺术画作、设计素材、报告图表等,提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使

Android中Dialog的使用详解

《Android中Dialog的使用详解》Dialog(对话框)是Android中常用的UI组件,用于临时显示重要信息或获取用户输入,本文给大家介绍Android中Dialog的使用,感兴趣的朋友一起... 目录android中Dialog的使用详解1. 基本Dialog类型1.1 AlertDialog(

C#数据结构之字符串(string)详解

《C#数据结构之字符串(string)详解》:本文主要介绍C#数据结构之字符串(string),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录转义字符序列字符串的创建字符串的声明null字符串与空字符串重复单字符字符串的构造字符串的属性和常用方法属性常用方法总结摘

Java中StopWatch的使用示例详解

《Java中StopWatch的使用示例详解》stopWatch是org.springframework.util包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,这篇文章主要介绍... 目录stopWatch 是org.springframework.util 包下的一个工具类,使用它

Java进行文件格式校验的方案详解

《Java进行文件格式校验的方案详解》这篇文章主要为大家详细介绍了Java中进行文件格式校验的相关方案,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、背景异常现象原因排查用户的无心之过二、解决方案Magandroidic Number判断主流检测库对比Tika的使用区分zip

Java实现时间与字符串互相转换详解

《Java实现时间与字符串互相转换详解》这篇文章主要为大家详细介绍了Java中实现时间与字符串互相转换的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、日期格式化为字符串(一)使用预定义格式(二)自定义格式二、字符串解析为日期(一)解析ISO格式字符串(二)解析自定义