本文共 8255 字,大约阅读时间需要 27 分钟。
大部分资料都讲了很多东西却最终没有让我搞清楚怎么用 DBus,不就是一个 IPC 通信的工具么?就没有一点实用些的资料么?看了很多资料之后还是觉得只见树木不见森林。仔细整理下思路,觉得还是应该从最基本的方面入门,先从 的 C API 入手学习,有了这些知识,就算麻烦,也可以先在完成一个基本功能的例子程序的同时大概的知道 DBus 的运行机制。 在网上找到这么一篇文章:http://www.matthew.ath.cx/misc/dbus, 正合我意,下面的内容基本是对这篇文章的翻译和扩充。 注意: 翻译没有得到原文作者同意,原文也很简单易懂,最好去读原文。如果收到投诉,我会立即撤掉本文的。 本文不是一篇好的 DBus 入门,有很多基本的东西不在记述之内。 一般情况下不会直接使用 C API 进行 DBus 的编程,而是使用某种 DBus-binding,但我觉得理解 DBus 的 C API 对完整地理解 DBus 是非常重要的。虽然 DBus 是用 C 写的,而且本文写的是 C API,但是 DBus 设计中充满的面向对象的思想,请注意。
一、共通部分的代码
在使用 DBus 进行通信的时候,有一些代码是无论如何都会使用到的。首先,你必须要连接上 Dbus,一般来说,系统中会有一个 System Bus 和一个 Session Bus(他们的差别,请参考我另外的笔记)。其次,你需要在 Dbus 中注册一个名字,用于标识自己。为了简单起见,这里先不考虑重名的情况:DBusError err;DBusConnection* conn;int ret;// initialise the errorsdbus_error_init(&err); // connect to the busconn = dbus_bus_get(DBUS_BUS_SESSION, &err);if (dbus_error_is_set(&err)) { fprintf(stderr, "Connection Error (%s)\n", err.message); dbus_error_free(&err);}if (NULL == conn) { exit(1);}// request a name on the busret = dbus_bus_request_name(conn, "test.method.server", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);if (dbus_error_is_set(&err)) { fprintf(stderr, "Name Error (%s)\n", err.message); dbus_error_free(&err);}if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) { exit(1);}一般来说,连接上 Dbus 和注册一个名称,应该是在程序最开始运行的时候就会进行的操作。
当然,在程序的结束的时候,需要关闭掉与 Dbus 的连接。使用下面的函数:
dbus_connection_close(conn);
二、发送信号(Sending Signal) 信号是一种广播的消息,你可以简单的发出一个信号,这样,所有连接在 DBus 总线上并注册了接受对应信号的进程,都会收到这个信号。为了发出一个信号,需要的只是创建一个 DBusMessage 对象来代表信号,然后追加上一些需要发出的参数,就可以发向总线了。发完之后还需要释放掉 Message。如果内存不足的话,这下面不少函数都会返回 false,所以一般情况下你都需要处理这些情况的返回值。
dbus_uint32_t serial = 0; // unique number to associate replies with requestsDBusMessage* msg;DBusMessageIter args; // create a signal and check for errorsmsg = dbus_message_new_signal("/test/signal/Object", // object name of the signal "test.signal.Type", // interface name of the signal "Test"); // name of the signalif (NULL == msg){ fprintf(stderr, "Message Null\n"); exit(1);} // append arguments onto signaldbus_message_iter_init_append(msg, &args);if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &sigvalue)) { fprintf(stderr, "Out Of Memory!\n"); exit(1);} // send the message and flush the connectionif (!dbus_connection_send(conn, msg, &serial)) { fprintf(stderr, "Out Of Memory!\n"); exit(1);}dbus_connection_flush(conn); // free the messagedbus_message_unref(msg);三、调用方法(Calling a Method) 调用一个远程方法(remote method)与发送一个信号(sending a signal)是很类似的。需要创建一个 DBusMessage,然后通过注册在 DBus 上的名称指定发送的对象。然后追加相应的参数,但调用方法分为两种,一种是阻塞式的,另一种则可以异步调用。异步调用的时候会得到一个 DBusMessage* 的返回,从这个 DBusMessage 中可以获取一些返回的参数。
调用方法1:
DBusMessage* msg;DBusMessageIter args;DBusPendingCall* pending; msg = dbus_message_new_method_call("test.method.server", // target for the method call "/test/method/Object", // object to call on "test.method.Type", // interface to call on "Method"); // method nameif (NULL == msg) { fprintf(stderr, "Message Null\n"); exit(1);} // append argumentsdbus_message_iter_init_append(msg, &args);if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, ¶m)) { fprintf(stderr, "Out Of Memory!\n"); exit(1);} // send message and get a handle for a replyif (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout fprintf(stderr, "Out Of Memory!\n"); exit(1);}if (NULL == pending) { fprintf(stderr, "Pending Call Null\n"); exit(1);}dbus_connection_flush(conn); // free messagedbus_message_unref(msg);调用方法2:
bool stat;dbus_uint32_t level; // block until we receive a replydbus_pending_call_block(pending); // get the reply messagemsg = dbus_pending_call_steal_reply(pending);if (NULL == msg) { fprintf(stderr, "Reply Null\n"); exit(1);}// free the pending message handledbus_pending_call_unref(pending); // read the parametersif (!dbus_message_iter_init(msg, &args)) fprintf(stderr, "Message has no arguments!\n");else if (DBUS_TYPE_BOOLEAN != dbus_message_iter_get_arg_type(&args)) fprintf(stderr, "Argument is not boolean!\n");else dbus_message_iter_get_basic(&args, &stat); if (!dbus_message_iter_next(&args)) fprintf(stderr, "Message has too few arguments!\n");else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args)) fprintf(stderr, "Argument is not int!\n");else dbus_message_iter_get_basic(&args, &level); printf("Got Reply: %d, %d\n", stat, level); // free reply and close connectiondbus_message_unref(msg);四、接收消息(Receiving a Signal) 接下来的两种操作主要是从总线从读取消息并处理这些消息。 要接收一个消息,你首先需要告诉 你对什么样的消息感兴趣:
// add a rule for which messages we want to seedbus_bus_add_match(conn, "type='signal',interface='test.signal.Type'", &err); // see signals from the given interfacedbus_connection_flush(conn);if (dbus_error_is_set(&err)) { fprintf(stderr, "Match Error (%s)\n", err.message); exit(1);}然后,进程就可以在一个循环中等待这类消息的发生了:
/ loop listening for signals being emmittedwhile (true) { // non blocking read of the next available message dbus_connection_read_write(conn, 0); msg = dbus_connection_pop_message(conn); // loop again if we haven't read a message if (NULL == msg) { sleep(1); continue; } // check if the message is a signal from the correct interface and with the correct name if (dbus_message_is_signal(msg, "test.signal.Type", "Test")) { // read the parameters if (!dbus_message_iter_init(msg, &args)) fprintf(stderr, "Message has no arguments!\n"); else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) fprintf(stderr, "Argument is not string!\n"); else { dbus_message_iter_get_basic(&args, &sigvalue); printf("Got Signal with value %s\n", sigvalue); } } // free the message dbus_message_unref(msg);}五、提供被远程调用的方法(Exposing a Method to be called) 在第二节中,我们看到了调用一个远程方法,这节就是告诉我们怎么样提供一个方法让别的应用程序调用。用下面的程序,就可以把方法关联在那些提供给外部的方法上,并解析出相应的参数,最后构建一个消息返回给调用方法的应用程序。
提供被远程调用的方法1:
// loop, testing for new messageswhile (true) { // non blocking read of the next available message dbus_connection_read_write(conn, 0); msg = dbus_connection_pop_message(conn); // loop again if we haven't got a message if (NULL == msg) { sleep(1); continue; } // check this is a method call for the right interface and method if (dbus_message_is_method_call(msg, "test.method.Type", "Method")) reply_to_method_call(msg, conn); // free the message dbus_message_unref(msg);}提供被远程调用的方法2:
void reply_to_method_call(DBusMessage* msg, DBusConnection* conn){ DBusMessage* reply; DBusMessageIter args; DBusConnection* conn; bool stat = true; dbus_uint32_t level = 21614; dbus_uint32_t serial = 0; char* param = ""; // read the arguments if (!dbus_message_iter_init(msg, &args)) fprintf(stderr, "Message has no arguments!\n"); else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) fprintf(stderr, "Argument is not string!\n"); else dbus_message_iter_get_basic(&args, ¶m); printf("Method called with %s\n", param); // create a reply from the message reply = dbus_message_new_method_return(msg); // add the arguments to the reply dbus_message_iter_init_append(reply, &args); if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_BOOLEAN, &stat)) { fprintf(stderr, "Out Of Memory!\n"); exit(1); } if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &level)) { fprintf(stderr, "Out Of Memory!\n"); exit(1); } // send the reply && flush the connection if (!dbus_connection_send(conn, reply, &serial)) { fprintf(stderr, "Out Of Memory!\n"); exit(1); } dbus_connection_flush(conn); // free the reply dbus_message_unref(reply);}这就基本上全部了。但用这些来理解 DBus 显然还远远不够。接下来,就要对这些程序以及背后的理念进行具体的探究了。
转载自:http://www.cnblogs.com/liyiwen/archive/2012/12/02/2798876.html
参考资料: