zoukankan      html  css  js  c++  java
  • DBus 入门与应用 -- DBus 的 C 编程接口


    转载请注明出处。               作者: 唐风  


    最近在学 Dbus,不过总是不得其门而入。

    大部分资料都讲了很多东西却最终没有让我搞清楚怎么用 DBus,不就是一个 IPC 通信的工具么?就没有一点实用些的资料么?看了很多资料之后还是觉得只见树木不见森林。仔细整理下思路,觉得还是应该从最基本的方面入门,先从 DBus 的 C API 入手学习,有了这些知识,就算麻烦,也可以先在完成一个基本功能的例子程序的同时大概的知道 DBus 的运行机制。

    在网上找到这么一篇文章:http://www.matthew.ath.cx/misc/dbus, 正合我意,下面的内容基本是对这篇文章的翻译和扩充。

    注意:

    1. 翻译没有得到原文作者同意,原文也很简单易懂,最好去读原文。如果收到投诉,我会立即撤掉本文的。
    2. 本文不是一篇好的 DBus 入门,有很多基本的东西不在记述之内。
    3. 一般情况下不会直接使用 C API 进行 DBus 的编程,而是使用某种 DBus-binding,但我觉得理解 DBus 的 C API 对完整地理解 DBus 是非常重要的。
    4. 虽然 DBus 是用 C 写的,而且本文写的是 C API,但是 DBus 设计中充满的面向对象的思想,请注意。


    一、共通部分的代码

    在使用 DBus 进行通信的时候,有一些代码是无论如何都会使用到的。首先,你必须要连接上 Dbus,一般来说,系统中会有一个 System Bus 和一个 Session Bus(他们的差别,请参考我另外的笔记)。其次,你需要在 Dbus 中注册一个名字,用于标识自己。为了简单起见,这里先不考虑重名的情况:

    共通用代码
    1. DBusError err;
    2. DBusConnection* conn;
    3. int ret;
    4. // initialise the errors
    5. dbus_error_init(&err);
    6.  
    7. // connect to the bus
    8. conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
    9. if (dbus_error_is_set(&err)) {
    10.     fprintf(stderr, "Connection Error (%s)\n", err.message);
    11.     dbus_error_free(&err);
    12. }
    13. if (NULL == conn) {
    14.     exit(1);
    15. }
    16. // request a name on the bus
    17. ret = dbus_bus_request_name(conn, "test.method.server",
    18.                             DBUS_NAME_FLAG_REPLACE_EXISTING
    19.                             , &err);
    20. if (dbus_error_is_set(&err)) {
    21.     fprintf(stderr, "Name Error (%s)\n", err.message);
    22.     dbus_error_free(&err);
    23. }
    24. if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
    25.     exit(1);
    26. }

    一般来说,连接上 Dbus 和注册一个名称,应该是在程序最开始运行的时候就会进行的操作。

    当然,在程序的结束的时候,需要关闭掉与 Dbus 的连接。使用下面的函数:

    Code Snippet
    1. dbus_connection_close(conn);

    二、发送信号(Sending Signal)

    信号是一种广播的消息,你可以简单的发出一个信号,这样,所有连接在 DBus 总线上并注册了接受对应信号的进程,都会收到这个信号。为了发出一个信号,需要的只是创建一个 DBusMessage 对象来代表信号,然后追加上一些需要发出的参数,就可以发向总线了。发完之后还需要释放掉 Message。如果内存不足的话,这下面不少函数都会返回 false,所以一般情况下你都需要处理这些情况的返回值。

    发送信号
    1. dbus_uint32_t serial = 0; // unique number to associate replies with requests
    2. DBusMessage* msg;
    3. DBusMessageIter args;
    4.  
    5. // create a signal and check for errors
    6. msg = dbus_message_new_signal("/test/signal/Object", // object name of the signal
    7.                               "test.signal.Type", // interface name of the signal
    8.                               "Test"); // name of the signal
    9. if (NULL == msg)
    10. {
    11.     fprintf(stderr, "Message Null\n");
    12.     exit(1);
    13. }
    14.  
    15. // append arguments onto signal
    16. dbus_message_iter_init_append(msg, &args);
    17. if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &sigvalue)) {
    18.     fprintf(stderr, "Out Of Memory!\n");
    19.     exit(1);
    20. }
    21.  
    22. // send the message and flush the connection
    23. if (!dbus_connection_send(conn, msg, &serial)) {
    24.     fprintf(stderr, "Out Of Memory!\n");
    25.     exit(1);
    26. }
    27. dbus_connection_flush(conn);
    28.  
    29. // free the message
    30. dbus_message_unref(msg);

    三、调用方法(Calling a Method)

    调用一个远程方法(remote method)与发送一个信号(sending a signal)是很类似的。需要创建一个 DBusMessage,然后通过注册在 DBus 上的名称指定发送的对象。然后追加相应的参数,但调用方法分为两种,一种是阻塞式的,另一种则可以异步调用。异步调用的时候会得到一个 DBusMessage* 的返回,从这个 DBusMessage 中可以获取一些返回的参数。

    调用方法1
    1. DBusMessage* msg;
    2. DBusMessageIter args;
    3. DBusPendingCall* pending;
    4.  
    5. msg = dbus_message_new_method_call("test.method.server", // target for the method call
    6.                                    "/test/method/Object", // object to call on
    7.                                    "test.method.Type", // interface to call on
    8.                                    "Method"); // method name
    9. if (NULL == msg) {
    10.     fprintf(stderr, "Message Null\n");
    11.     exit(1);
    12. }
    13.  
    14. // append arguments
    15. dbus_message_iter_init_append(msg, &args);
    16. if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &param)) {
    17.     fprintf(stderr, "Out Of Memory!\n");
    18.     exit(1);
    19. }
    20.  
    21. // send message and get a handle for a reply
    22. if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
    23.     fprintf(stderr, "Out Of Memory!\n");
    24.     exit(1);
    25. }
    26. if (NULL == pending) {
    27.     fprintf(stderr, "Pending Call Null\n");
    28.     exit(1);
    29. }
    30. dbus_connection_flush(conn);
    31.  
    32. // free message
    33. dbus_message_unref(msg);

    调用方法2
    1. bool stat;
    2. dbus_uint32_t level;
    3.  
    4. // block until we receive a reply
    5. dbus_pending_call_block(pending);
    6.  
    7. // get the reply message
    8. msg = dbus_pending_call_steal_reply(pending);
    9. if (NULL == msg) {
    10.     fprintf(stderr, "Reply Null\n");
    11.     exit(1);
    12. }
    13. // free the pending message handle
    14. dbus_pending_call_unref(pending);
    15.  
    16. // read the parameters
    17. if (!dbus_message_iter_init(msg, &args))
    18.     fprintf(stderr, "Message has no arguments!\n");
    19. else if (DBUS_TYPE_BOOLEAN != dbus_message_iter_get_arg_type(&args))
    20.     fprintf(stderr, "Argument is not boolean!\n");
    21. else
    22.     dbus_message_iter_get_basic(&args, &stat);
    23.  
    24. if (!dbus_message_iter_next(&args))
    25.     fprintf(stderr, "Message has too few arguments!\n");
    26. else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
    27.     fprintf(stderr, "Argument is not int!\n");
    28. else
    29.     dbus_message_iter_get_basic(&args, &level);
    30.  
    31. printf("Got Reply: %d, %d\n", stat, level);
    32.  
    33. // free reply and close connection
    34. dbus_message_unref(msg);

    四、接收消息(Receiving a Signal)

    接下来的两种操作主要是从总线从读取消息并处理这些消息。

    要接收一个消息,你首先需要告诉 DBus 你对什么样的消息感兴趣:

    接收消息1
    1. // add a rule for which messages we want to see
    2. dbus_bus_add_match(conn,
    3.                    "type='signal',interface='test.signal.Type'",
    4.                    &err); // see signals from the given interface
    5. dbus_connection_flush(conn);
    6. if (dbus_error_is_set(&err)) {
    7.     fprintf(stderr, "Match Error (%s)\n", err.message);
    8.     exit(1);
    9. }

    然后,进程就可以在一个循环中等待这类消息的发生了:

    接收消息2
    1. / loop listening for signals being emmitted
    2. while (true) {
    3.  
    4.     // non blocking read of the next available message
    5.     dbus_connection_read_write(conn, 0);
    6.     msg = dbus_connection_pop_message(conn);
    7.  
    8.     // loop again if we haven't read a message
    9.     if (NULL == msg) {
    10.         sleep(1);
    11.         continue;
    12.     }
    13.  
    14.     // check if the message is a signal from the correct interface and with the correct name
    15.     if (dbus_message_is_signal(msg, "test.signal.Type", "Test")) {
    16.         // read the parameters
    17.         if (!dbus_message_iter_init(msg, &args))
    18.             fprintf(stderr, "Message has no arguments!\n");
    19.         else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
    20.             fprintf(stderr, "Argument is not string!\n");
    21.         else {
    22.             dbus_message_iter_get_basic(&args, &sigvalue);
    23.             printf("Got Signal with value %s\n", sigvalue);
    24.         }
    25.     }
    26.  
    27.     // free the message
    28.     dbus_message_unref(msg);
    29. }

    五、提供被远程调用的方法(Exposing a Method to be called)

    在第二节中,我们看到了调用一个远程方法,这节就是告诉我们怎么样提供一个方法让别的应用程序调用。用下面的程序,就可以把方法关联在那些提供给外部的方法上,并解析出相应的参数,最后构建一个消息返回给调用方法的应用程序。

    提供被远程调用的方法1
    1. // loop, testing for new messages
    2. while (true) {
    3.     // non blocking read of the next available message
    4.     dbus_connection_read_write(conn, 0);
    5.     msg = dbus_connection_pop_message(conn);
    6.   
    7.     // loop again if we haven't got a message
    8.     if (NULL == msg) {
    9.         sleep(1);
    10.         continue;
    11.     }
    12.  
    13.     // check this is a method call for the right interface and method
    14.     if (dbus_message_is_method_call(msg, "test.method.Type", "Method"))
    15.         reply_to_method_call(msg, conn);
    16.  
    17.     // free the message
    18.     dbus_message_unref(msg);
    19. }
    提供被远程调用的方法2
    1. void reply_to_method_call(DBusMessage* msg, DBusConnection* conn)
    2. {
    3.     DBusMessage* reply;
    4.     DBusMessageIter args;
    5.     DBusConnection* conn;
    6.     bool stat = true;
    7.     dbus_uint32_t level = 21614;
    8.     dbus_uint32_t serial = 0;
    9.     char* param = "";
    10.  
    11.     // read the arguments
    12.     if (!dbus_message_iter_init(msg, &args))
    13.         fprintf(stderr, "Message has no arguments!\n");
    14.     else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args))
    15.         fprintf(stderr, "Argument is not string!\n");
    16.     else
    17.         dbus_message_iter_get_basic(&args, &param);
    18.     printf("Method called with %s\n", param);
    19.  
    20.     // create a reply from the message
    21.     reply = dbus_message_new_method_return(msg);
    22.  
    23.     // add the arguments to the reply
    24.     dbus_message_iter_init_append(reply, &args);
    25.     if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_BOOLEAN, &stat)) {
    26.         fprintf(stderr, "Out Of Memory!\n");
    27.         exit(1);
    28.     }
    29.     if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &level)) {
    30.         fprintf(stderr, "Out Of Memory!\n");
    31.         exit(1);
    32.     }
    33.  
    34.     // send the reply && flush the connection
    35.     if (!dbus_connection_send(conn, reply, &serial)) {
    36.         fprintf(stderr, "Out Of Memory!\n");
    37.         exit(1);
    38.     }
    39.     dbus_connection_flush(conn);
    40.  
    41.     // free the reply
    42.     dbus_message_unref(reply);
    43. }

    这就基本上全部了。但用这些来理解 DBus 显然还远远不够。接下来,就要对这些程序以及背后的理念进行具体的探究了。

    ---- 总会有一个人需要你的分享~! 唐风: www.cnblogs.com/muxue ------
  • 相关阅读:
    php详解和优化
    接口
    抽象类
    对象转型
    面向对象2
    Super关键字
    Object类介绍
    有效处理java异常的三个原则
    this关键字
    equals方法
  • 原文地址:https://www.cnblogs.com/muxue/p/2798876.html
Copyright © 2011-2022 走看看