QDBus使用

2 篇文章 0 订阅

一、服务端注册

// 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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值