QDBus使用

QDBus使用

一、服务端注册

// main.cpp
#include <QCoreApplication>
#include <QtDBus/QDBusConnection>
#include <QDebug>
#include <QtDBus/QDBusError>
#include <iostream>
#include "test.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //建立到session bus的连接
    QDBusConnection connection = QDBusConnection::systemBus();
    //在session bus上注册名为com.nde.chattr的服务
    if(!connection.registerService("com.my.test"))
    {
        qDebug() << "error:" << connection.lastError().message();
        exit(-1);
    }

    Test object;
    // 注册名为/ndeChattr的对象,把类Object所有槽函数导出为object的method
    connection.registerObject("/object", "com.my.test", &object, QDBusConnection::ExportAllSlots);

    return a.exec();
}
//test.h
#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QStringList>
#include <QSettings>

class Test : public QObject
{
    Q_OBJECT
    //定义Interface名称为com.my.test
    Q_CLASSINFO("D-Bus Interface", "com.my.test")
public:
    explicit Test(QObject *parent = nullptr);

public slots:
    void value();  

private:
    int process_count;
};

#endif // TEST_H
//test.cpp
#include "ndechattr.h"
#include <iostream>

Test::Test(QObject *parent) :
    QObject(parent),
    process_count(0)
{
    
}

void Test::value()
{
	std::cout << process_count << std::endl;
}

二、配置服务端自动启动

方法一:当客户端调用到接口时自动启动服务

编写配置文件/usr/share/dbus-1/services/com.my.test.service

[D-BUS Service]
Name=com.my.test
Exec=/usr/bin/test

方法二:开机自启动服务

/usr/lib/systemd/system/test.service

[Unit]
Description=My Test Service

[Service]
ExecStart=/usr/bin/test
Restart=always

[Install]
WantedBy=multi-user.target

/etc/dbus-1/system.d/com.nde.chattr.conf

<!DOCTYPE busconfig PUBLIC
 "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>

  <!-- Only root can own the service -->
  <policy user="root">
    <allow own="com.my.test"/>
  </policy>

  <policy context="default">
    <allow send_destination="com.my.test" send_interface="org.freedesktop.DBus.Properties"/>
    <allow send_destination="com.my.test" send_interface="org.freedesktop.DBus.Introspectable"/>
    <allow send_destination="com.my.test" send_interface="com.my.test"/>
  </policy>

</busconfig>

设定启动服务
systemctl enable test.service
systemctl start test.service

三、客户端调用:dbus-send

dbus-send --system --print-reply --dest=com.my.test /object com.my.test.value

上一篇:Asp.Net MVC @Html.TextBox 只允许输入数字问题


下一篇:jquery中this与 this 的用法区别