D-Bus introduction in Perl

As stated in Wikipedia :

D-Bus (Desktop Bus) is a simple inter-process communication (IPC) system for software applications to communicate with one another.

This post provides a simple code snippet in Perl to help you getting started with D-Bus programming.

D-Bus is used by many applications to provide users with a more tightly integrated desktop environment. Basically, an application can use D-Bus to provide services as well as to notify other application when a specific event occurs.

For example, the instant messaging client Pidgin will send a signal on D-Bus when a buddy on the contact list will connect. An application listening for this signal on the D-Bus pick it up (think inter-process messages) and then use D-Bus to ask extra informations to Pidgin about this buddy (think remote procedure call).

As I wanted to experiment with D-Bus, I’ve put this little example in practice. The code is pretty much self explanatory. It is coded in Perl as this is the language I use the most. Besides there are already plenty of examples of D-Bus programming in Python, but not so many in Perl.

#! /usr/bin/perl

use strict;
use warnings;

use Net::DBus;
use Net::DBus::Reactor;

# There is the system bus and the session bus. Here we are
# interested in the session bus
my $bus = Net::DBus->session;

# we connect the services Pidgin offers through D-Bus
my $purple = $bus->get_service('im.pidgin.purple.PurpleService');
my $object = $purple->get_object('/im/pidgin/purple/PurpleObject', 'im.pidgin.purple.PurpleInterface');

# we register a signal handler for when a connection occurs
$object->connect_to_signal('BuddySignedOn',
    sub {
        my $buddyId = shift;
        print "BuddySignedOn:", $object->PurpleBuddyGetAlias($buddyId), "\n";
    }
);

# and we start the main loop where the events are processed
my $reactor = Net::DBus::Reactor->main();
$reactor->run();
exit(0);

So all in all it makes it easy to offer the user an integrated environment thanks to D-Bus.

Imagine that, every time a new song is played in your music player, a signal is sent on the bus and your instant messaging client picks it up to display it in your status ? Easy to do with D-Bus ! And of course there are endless possibilities to make applications work together !