用新型D-BUS与Linux桌面应用程序通讯
用例
尽管 D-BUS 相对较新,但是却迅速地得到了采用。如前所述,可以构建具有 D-BUS 支持的 udev 以使得当热插拔(hot-plug)设备时它可以发送一个信号。任何应用程序都可以侦听这些事件并当接收到这些事件时执行动作。例如,gnome-volume-manager 可以检测到 USB 存储棒的插入并自动挂载它;或者,当插入一个数码相机时它可以自动下载照片。
一个更为有趣但很不实用的例子是 Jamboree 和 Ringaling 的结合。Jamboree 是一个简单的音乐播放器,它具有 D-BUS 接口,以使得它可以被告知播放、到下一首歌、改变音量等等。Ringaling 是一个小程序,它打开 /dev/ttyS0(一个串行端口)并观察接收到的内容。当 Ringaling 发现文本“RING”时,就通过 D-BUS 告知 Jamboree 减小音量。最终的结果是,如果您的计算机上插入了一个调制解调器,而且电话铃响,则音乐音量就会为您减小。这 正是计算机所追求的!
代码示例
现在,让我们来接触一些使用 D-BUS 代码的示例。
dbus-ping-send.c 每秒通过会话总线发送一个参数为字符串“Ping!”的信号。我使用 Glib 来管理总线,以使得我不需要自己来处理总线的连接细节。
清单 1. dbus-ping-send.c
#include <glib.h>
#include <dbus/dbus-glib.h>
static gboolean send_ping (DBusConnection *bus);
int
main (int argc, char **argv)
{
GMainLoop *loop;
DBusConnection *bus;
DBusError error;
/* Create a new event loop to run in */
loop = g_main_loop_new (NULL, FALSE);
/* Get a connection to the session bus */
dbus_error_init (&error);
bus = dbus_bus_get (DBUS_BUS_SESSION, &error);
if (!bus) {
g_warning ("Failed to connect to the D-BUS
daemon: %s", error.message);
dbus_error_free (&error);
return 1;
}
/* Set up this connection to work in a GLib event loop */
dbus_connection_setup_with_g_main (bus, NULL);
/* Every second call send_ping() with the bus as an argument*/
g_timeout_add (1000, (GSourceFunc)send_ping, bus);
/* Start the event loop */
g_main_loop_run (loop);
return 0;
}
static gboolean
send_ping (DBusConnection *bus)
{
DBusMessage *message;
/* Create a new signal "Ping" on the
"com.burtonini.dbus.Signal" interface,
* from the object "/com/burtonini/dbus/ping". */
message = dbus_message_new_signal
("/com/burtonini/dbus/ping",
"com.burtonini.dbus.Signal", "Ping");
/* Append the string "Ping!" to the signal */
dbus_message_append_args (message,
DBUS_TYPE_STRING, "Ping!",
DBUS_TYPE_INVALID);
/* Send the signal */
dbus_connection_send (bus, message, NULL);
/* Free the signal now we have finished with it */
dbus_message_unref (message);
/* Tell the user we send a signal */
g_print("Ping!\n");
/* Return TRUE to tell the event loop
we want to be called again */
return TRUE;
}
main 函数创建一个 GLib 事件循环,获得会话总线的一个连接,并将 D-BUS 事件处理集成到 Glib 事件循环之中。然后它创建了一个名为 send_ping 间隔为一秒的计时器,并启动事件循环。












文章评论
共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面