最近的工作涉及到DBUS通信,所以这里做一下总结,也是即学即用所以了解的没有那么深入,环境搭建这里就不谈了,这里说说具体的操作流程以及代码的实现。
我们这里按CS的模式来讲,我们这里会有两个C文件,一个是服务端代码,一个是客户端代码,对了还有一个XML文件。
首先当然是先写好这两个代码,然后就是编译了,编译首先先要编译这个XML文件,编译这个XML文件我们这里要利用到DBUS-BINDING-TOOL这个工具:
dbus-binding-tool --mode=glib-server --prefix=netsetserver netset.xml>netset_server.h
dbus-binding-tool --mode=glib-client --prefix=netsetserver netset.xml>netset_client.h
注意这两句只有MODE是不一样的,所以生成的头文件一个是客户端的一个是服务端的,这里举个NETSET.XML这个文件的示例:
<?xml version="1.0" encoding="UTF-8"?>
<node name="/test/example/server">
<interface name="test.example.ServerInterface">
<method name="getmacip">
<arg name="device" type="s" direction="in"/>
<arg name="macip" type="ay" direction="out"/>
</method>
</interface>
</node>
这里有一个节点node,里面包含一个接口interface,这个接口里头包含一个方法method,方法也就是函数啦,可以理解成这个函数是这样的getmacip(char *device,struct xxx macip),其中device是输入参数,macip是输出参数,注意我这里展示的是比较难的结构体的传递,数据类型是ay,这里涉及到一个用容器存储数据的技巧。
好了现在看看客户端是如何实现的:
#include <dbus/dbus.h>
#include <dbus/dbus-glib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAXIPNUM 1024
typedef struct addr
{
unsigned char mac[20];
unsigned char ip[MAXIPNUM*16];
}Addr;
typedef struct testa
{
int a;
char b[20];
}Testa;
typedef struct testb
{
int c;
Testa t;
}Testb;
static void
lose(const char *str, ...)
{
va_list args;
va_start(args, str);
vfprintf(stderr, str, args);
fputc('/n', stderr);
va_end(args);
exit(1);
}
static void
lose_gerror(const char *prefix, GError *error)
{