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;
}
相关推荐
北冥湖畔的燕雀17 分钟前
Linux线程编程核心指南
linux·服务器·网络
倔强的石头10629 分钟前
【Linux 指南】文件系统系列(一):磁盘底层原理 —— 从物理结构到 CHS与LBA 寻址全解析
linux·运维·服务器
南汁bbj38 分钟前
彻底解决!Milvus远程连接报错code=2、gRPC超时问题(Windows访问Linux服务终极方案)
linux·windows·milvus
宁小法1 小时前
Linux上 log日志很大,如何获取部分内容?
linux·日志文件·传输
zhangrelay1 小时前
云课实践速通系列-基础篇汇总-必修-通识基础和专业基础-2026--工科--自动化、电气、机器人、测控等
linux·笔记·单片机·学习·ubuntu·机器人·自动化
陶然同学2 小时前
【Linux及Shell】VMware&Ubuntu&Xshell安装
linux·运维·xshell8·xftp8
咖喱o2 小时前
DHCP
linux·运维·服务器·网络
IMPYLH2 小时前
Linux 的 touch 命令
linux·运维·服务器·bash
lzh200409193 小时前
深入学习Linux进程间通信:共享内存
linux·c++
ErizJ3 小时前
Linux|学习笔记
linux·笔记·学习