Waiting for a DBus service to be available in Qt Waiting for a DBus service to be available in Qt linux linux

Waiting for a DBus service to be available in Qt


Ok, since no one answered, I've found the answer in the meantime:

You want to watch NameOwnerChanged:

// subscribe to notifications about when a service is registered/unregistered   connect(QDBusConnection::sessionBus().interface(),           SIGNAL(serviceOwnerChanged(QString,QString,QString)),           this,SLOT(serviceOwnerChanged(QString,QString,QString)));

and

void VcsApplicationController::serviceOwnerChanged(const QString &name,                                              const QString &oldOwner,                                              const QString &newOwner){    Q_UNUSED(oldOwner);    if (name == "com.foo.bar.FooService")    {        qLog(Whatever) << "serviceOwnerChanged" << name << oldOwner << newOwner;        if (!newOwner.isEmpty())        {            // New owner in town            emit Initialized();            // or if you control the interface and both sides, you can wait for            // a "Ready()" signal before declaring FooService ready for business.        }        else        {            // indicate we've lost connection, etc            emit Uninitialized();        }    }}

Note that there may be race conditions with doing methods on FooService from within serviceOwnerChanged - I'm not sure yet if they're a side-effect of the binding (dbus-c++ in my test case), or inherent in the design of dbus (possible - no on on the dbus mailing list will answer the question). If there is a real race condition, you can wait on a Ready()/whatever signal, if you control the DBus API. If you don't control the other end, you can add a very short delay or you can also watch AddMatch() to make sure the new owner has added a match on the name as well.


With Qt 5.3, serviceOwnerChanged is deprecated. Use QDBusServiceWatcher which allows to watch for an specific service instead of all.