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();

    //创建返回消息reply
    reply = 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 name
    if (0 == access(DBUS_CLIENT_PID_FILE, F_OK))
        snprintf(name, sizeof(name), "%s%d", DBUS_RECEIVER_BUS_NAME, pid);
    else
        snprintf(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 handle
        dbus_pending_call_unref(pending);

        // read the Arguments
        if (!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:发送一个信号
        //根据图,我们给出这个信号的路径(即可以指向对象),接口,以及信号名,创建一个Message
        msg = 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]);
            else
                usage();
        }
    }
    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的例子就可以运行起来了,想详细了解这个例子需要自己去看例子的源码。


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值