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;
}
相关推荐
ambition2024244 分钟前
操作系统同步:读者-写者问题与读写公平法详解(附每个 PV 操作含义)
linux·开发语言·数据结构·unix
zmzmzmalo1 小时前
Linux ELF文件加载与内存管理揭秘
linux·网络·数据库
三言老师7 小时前
K8s集群运行时自动化运维全覆盖落地实操(下)
linux·运维·服务器·网络
ltl8 小时前
HAProxy HTX 与 HTTP 路径:内部表示、改写落点与协议分叉
linux
ltl8 小时前
可拆分 OS:CXL 内存池化如何动摇本地 DRAM 假设
linux
ltl8 小时前
Tetragon 强制执行:Override 与 SIGKILL 各自保证什么
linux
lengjingzju9 小时前
编译与调试完全指南—第6章 性能分析工具
linux
躺不平的理查德9 小时前
嵌入式 Linux 系统移植与 SD 卡量产镜像制作
linux·运维·服务器
一直走下去-明10 小时前
centos7无法安装tcpreplay
linux·运维
吹什么轩11 小时前
linux网络:TCP套接字基础
linux·网络·tcp/ip