Get on the D-BUS

Programs, the kernel and even your phone can keep you in touch and make the whole desktop work the way you want. Here's how D-BUS works, and how applications are using it.

Second, the session bus provides a mechanism for IPC and remote method invocation, possibly providing a unified system between GNOME and KDE. D-BUS aims to be a better CORBA than CORBA and a better DCOP than DCOP, satisfying the needs of both projects while providing additional features.

And, D-BUS does all this while remaining simple and efficient.

Adding D-BUS Support to Your Application

The core D-BUS API, written in C, is rather low-level and large. On top of this API, bindings integrate with programming languages and environments, including Glib, Python, Qt and Mono. On top of providing language wrappers, the bindings provide environment-specific features. For example, the Glib bindings treat D-BUS connections as GObjects and allow messaging to integrate into the Glib mainloop. The preferred use of D-BUS is definitely using language and environment-specific bindings, both for ease of use and improved functionality.

Let's look at some basic uses of D-BUS in your application. We first look at the C API and then poke at some D-BUS code using the Glib interface.

The D-BUS C API

Using D-BUS starts with including its header:


#include <dbus/dbus.h>

The first thing you probably want to do is connect to an existing bus. Recall from our initial D-BUS discussion that D-BUS provides two buses, the session and the system bus. Let's connect to the system bus:


DBusError error;
DBusConnection *conn;

dbus_error_init (&error);
conn = dbus_bus_get (DBUS_BUS_SYSTEM, &error);
if (!conn) {
    fprintf (stderr, "%s: %s\n",
             err.name, err.message);
    return 1;
}

Connecting to the system bus is a nice first step, but we want to be able to send messages from a well-known address. Let's acquire a service:


dbus_bus_acquire_service (conn, "org.pirate.parrot",
                          0, &err);
if (dbus_error_is_set (&err)) {
    fprintf (stderr, "%s: %s\n",
             err.name, err.message);
    dbus_connection_disconnect (conn);
    return;
}

Now that we are on the system bus and have acquired the org.pirate.parrot service, we can send messages originating from that address. Let's send a signal:


DBusMessage *msg;
DBusMessageIter iter;

/* create a new message of type signal */
msg = dbus_message_new_signal(
          "org/pirate/parrot/attr",
          "org.pirate.parrot.attr", "Feathers");

/* build the signal's payload up */
dbus_message_iter_init (msg, &iter);
dbus_message_iter_append_string (&iter, "Shiny");
dbus_message_iter_append_string (&iter,
                                 "Well Groomed");

/* send the message */
if (!dbus_connection_send (conn, msg, NULL))
        fprintf (stderr, "error sending message\n");

/* drop the reference count on the message */
dbus_message_unref (msg);

/* flush the connection buffer */
dbus_connection_flush (conn);

This sends the Feathers signal from org.pirate.parrot.attr with a payload consisting of two fields, each strings: Shiny and Well Groomed. Anyone listening on the system message bus with sufficient permissions can subscribe to this service and listen for the signal.

Disconnecting from the system message bus is a single function:

if (conn)
        dbus_connection_disconnect (conn);

The Glib Bindings

Glib (pronounced gee-lib) is the base library of GNOME. It is on top of Glib that Gtk+ (GNOME's GUI API) and the rest of GNOME is built. Glib provides several convenience functions, portability wrappers, a family of string functions and a complete object and type system—all in C.

The Glib library provides an object system and a mainloop, making object-based, event-driven programming possible, even in C. The D-BUS Glib bindings take advantage of these features. First, we want to include the right header files:


#include <dbus/dbus.h>
#include <dbus/dbus-glib.h>

Connecting to a specific message bus with the Glib bindings is easy:


DBusGConnection *conn;
GError *err = NULL;

conn = dbus_g_bus_get (DBUS_BUS_SESSION, &err);
if (!conn) {
        g_printerr ("Error: %s\n", error->message);
        g_error_free (error);
}

In this example, we connected to the per-user session bus. This call associates the connection with the Glib mainloop, allowing multiplexed I/O with the D-BUS messages.

The Glib bindings use the concept of proxy objects to represent instantiations of D-BUS connections associated with specific services. The proxy object is created with a single call:

DBusGProxy *proxy;

proxy = dbus_g_proxy_new_for_service (conn,
                                  "org.fruit.apple",
                                  "org/fruit/apple",
                                  "org.fruit.apple");

This time, instead of sending a signal, let's execute a remote method call. This is done using two functions. The first function invokes the remote method; the second retrieves the return value.

First, let's invoke the Peel remote method:

DBusGPendingCall *call;

call = dbus_g_proxy_begin_call (proxy,
                    "Peel", DBUS_TYPE_INVALID);

Now let's retrieve-check for errors and retrieve the results of the method call:


GError *err = NULL;
int ret;

if (!dbus_g_proxy_end_call (proxy, call,
                          &err, DBUS_TYPE_INT32,
                          &ret, DBUS_TYPE_INVALID)) {
        g_printerr ("Error: %s\n", err->message);
        g_error_free (err);
}

The Peel function accepts a single parameter, an integer. If this call returned nonzero, it succeeded, and the variable ret holds the return value from this function. The data types that a specific method accepts are determined by the remote method. For example, we could not have passed DBUS_TYPE_STRING instead of DBUS_TYPE_INT32.

The main benefit of the Glib bindings is mainloop integration, allowing developers to manage multiple D-BUS messages intertwined with other I/O and UI events. The header file <dbus/dbus-glib.h> declares multiple functions for connecting D-BUS to the Glib mainloop.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Thanks...

Anonymous's picture

...for the nice article! Now I'll do some googling myself to find out how to use it in practice :-)

Thanks for this material, i was able to write program with this!

Naga Samrat Chowdary, Narla's picture

Thanks to Robert Love.
I am able to understand this material and i was succeed in writing small program.

Thanks,
Naga Samrat Chowdary, Narla

client side of the example

Anonymous's picture

If my understanding is correct, I should have a server object providing the method Peel to reply to the method request.Do I register it via "dbus_g_connection_lookup_g_object" and the object information via "void dbus_g_object_type_install_info"

Also when the server object get the Peel method, does it use "void dbus_g_method_return" to retun a message. Thx

Article is USELESS without

Anonymous's picture

Article is USELESS without examples showing real services or at least a link to where to find actual dbus channels that are present on a dbus-enabled linux system.

Useless? I don't think so...

Anonymous's picture

Yet another cut-and-paste-code-kiddie looking for someone else to write their code, instead of reading an article to learn concepts and then generate their own code.

I learn from examples

Anonymous's picture

yes it is not complete.

not true, this article is

Anonymous's picture

not true,

this article is not complete...

no completed sample for teste :( unable to view something...

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix