Ubuntu24.04 赋予 Qt 应用程序 修改系统时间 权限

1、情况简介

由于Ubuntu24.04对于安全性的考虑,以用户身份(非sudo)运行的应用程序无法直接修改内核时间,只能转而进行权限配置来修改系统时间。

2、具体操作

1、Settings-System-Date & Time 取消 Automatic Data & Time

2、GroundStation是我的应用名,pi是我的用户名,你需要自行改为自己的

bash 复制代码
sudo nano /etc/polkit-1/rules.d/allow-GroundStation-time-setting.rules

在文件中写入:

bash 复制代码
// Allow a specific user to set the time without a password
polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.timedate1.set-time" && subject.user == "pi") {
        return polkit.Result.YES;
    }
});

3、Qt程序示例

cpp 复制代码
bool HeartBeatReceiver::setSystemTime(u64 Timestamp_us)
{ 
    // --- 1. 将微秒时间戳转换为 QDateTime 对象并验证 ---
    QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(Timestamp_us / 1000);
    dateTime.setTimeSpec(Qt::UTC); // 时间戳通常是 UTC

    int year = dateTime.date().year();
    if (year < 2025 || year > 2030) {
        qDebug() << "Validation failed: Year " << year << " is not within the required range [2025, 2030].";
        return false;
    }
    qDebug() << "Validation passed. The year is " << year << ".";

    QProcess process;
    bool timeSetSuccess = false;

    // --- 2. 设置系统时间 ---

    QString formattedTime = dateTime.toString("yyyy-MM-dd hh:mm:ss");
    qDebug() << "Attempting to set system time..." << formattedTime;
    process.start("timedatectl", QStringList() << "set-time" << formattedTime);

    if (!process.waitForFinished(5000)) {
        qDebug() << "Error: 'timedatectl set-time' command timed out.";
    } else if (process.exitCode() == 0) {
        qDebug() << "System time set successfully!";
        timeSetSuccess = true;
    } else {
        qDebug() << "Error: Failed to set system time.";
        qDebug() << "Exit Code:" << process.exitCode();
        qDebug() << "Standard Error:" << process.readAllStandardError();
    }

    return timeSetSuccess;
}
相关推荐
zz_nj1 天前
工作的环境
linux·运维·服务器
极客先躯1 天前
如何自动提取Git指定时间段的修改文件?Win/Linux双平台解决方案
linux·git·elasticsearch
suijishengchengde1 天前
****LINUX时间同步配置*****
linux·运维
qiuqyue1 天前
基于虹软Linux Pro SDK的多路RTSP流并发接入、解码与帧级处理实践
linux·运维·网络
切糕师学AI1 天前
Linux 操作系统简介
linux
南烟斋..1 天前
GDB调试核心指南
linux·服务器
爱跑马的程序员1 天前
Linux 如何查看文件夹的大小(du、df、ls、find)
linux·运维·ubuntu
oMcLin1 天前
如何在 Ubuntu 22.04 LTS 上部署并优化 Magento 电商平台,提升高并发请求的响应速度与稳定性?
linux·运维·ubuntu
Qinti_mm1 天前
Linux io_uring:高性能异步I/O革命
linux·i/o·io_uring
优雅的38度1 天前
linux环境下,使用docker安装apache kafka (docker-compose)
linux·架构