Wednesday, December 30, 2015

D-Bus main loop programming

Over internet, there are many D-Bus examples like the following

1
2
3
4
5
6
7
8
9
10
11
12
13
while(true)
{
    dbus_connection_read_write();
    …
    pMessage = dbus_connection_pop_message();

    if (pMessage)
    {
        …
        dbus_message_unref(pMessage);
    }

}

This is incorrect.
  • dbus_connection_read_write() is a low level function bringing in raw data from lower transport layer.  It does not parse data and not aware of how many messages have been brought up.
  • dbus_message_pop_message() is a function popping 1 message from incoming queue/buffer. 
Overall, each dbus_connection_read_write() can effectively bring in more than 1 message.  Consequently, only popping 1 message after each dbus_connection_read_write() will potentially leave a large number of data in the incoming queue/buffer.

The correct loop is following

1
2
3
4
5
6
7
8
9
10
11
12
13
while(true)
{
    dbus_connection_read_write();
    …
    pMessage = dbus_connection_pop_message();

    while (pMessage)
    {
        …
        dbus_message_unref(pMessage);
    }

}

No comments:

Post a Comment