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;
}
相关推荐
小成202303202658 小时前
Linux高级02
linux·开发语言
mounter6258 小时前
【硬核前沿】CXL 深度解析:重塑数据中心架构的“高速公路”,Linux 内核如何应对挑战?-- CXL 协议详解与 LSF/MM 最新动态
linux·服务器·网络·架构·kernel
++==8 小时前
Linux 进程间通信与线程同步技术详解:IPC 机制、线程 API、同步工具与经典同步问题
linux
特长腿特长9 小时前
centos、ubantu系列机的用户和用户组的结构是什么?具体怎么配置?用户组权限怎么使用?这篇文章持续更新,帮助你复习linux的基础知识
linux·运维·centos
zzzyyy5389 小时前
Linux环境变量
linux·运维·服务器
pluvium279 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
无级程序员9 小时前
centos7 安装 llvm-toolset-7-clang出错的问题解决
linux·centos
CHHC188010 小时前
NetCore树莓派桌面应用程序
linux·运维·服务器
云栖梦泽11 小时前
Linux内核与驱动:9.Linux 驱动 API 封装
linux·c++
si莉亚12 小时前
ROS2安装EVO工具包
linux·开发语言·c++·开源