使用定时器监视当前PID 如果当前程序关闭 UI_Core.exe 也随之自动关闭实现方法

使用定时器监视当前PID 如果当前程序关闭 UI_Core.exe 也随之自动关闭实现方法

描述:

C++20 QT6.9 VS2022 中使用QProcess::startDetached("UI_Core.exe", QStringList(), QString(), &UI_Manage_pid);是启动目标程序 能否同时告诉目标程序当前宿主程序的PID,在UI_CORE.EXE中 使用定时器监视当前PID 如果当前程序关闭 UI_Core.exe 也随之自动关闭 如何实现。

  1. Parent: 启动并传递自身 PID
cpp 复制代码
#include <QCoreApplication>
#include <QProcess>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // 1) 获取宿主程序自身 PID
    qint64 hostPid = QCoreApplication::applicationPid();

    // 2) 构造参数列表,将 hostPid 作为第一个参数传给 UI_Core.exe
    QStringList args;
    args << QString::number(hostPid);

    // 3) 启动 UI_Core.exe 并取得它的 PID (可选)
    qint64 uiCorePid = 0;
    bool ok = QProcess::startDetached(
        "UI_Core.exe",
        args,
        /*workingDirectory=*/QString(),
        &uiCorePid
    );

    if (!ok) {
        qWarning() << "Failed to launch UI_Core.exe";
        return -1;
    }
    qDebug() << "Launched UI_Core.exe with PID" << uiCorePid;
    // ...宿主程序其余逻辑...
    return app.exec();
}

applicationPid() 从 Qt 6.2 起返回当前进程 ID。

我们在 QStringList 中塞入自己的 PID 字符串,子进程即可通过 QCoreApplication::arguments() 读取。

&uiCorePid 可以让你拿到子进程的 PID(方便日志或做进一步管理),但这不是必须的。

  1. Child: 读取 PID 并监视宿主进程
cpp 复制代码
#include <QApplication>       // 或 QCoreApplication
#include <QTimer>
#include <QDebug>
#ifdef Q_OS_WINDOWS
# include <windows.h>
#endif

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // 1) 解析命令行参数:arg1 应是宿主程序 PID
    qint64 hostPid = 0;
    const QStringList &args = QCoreApplication::arguments();
    if (args.size() >= 2) {
        hostPid = args.at(1).toLongLong();
        qDebug() << "Monitoring host PID =" << hostPid;
    } else {
        qWarning() << "No host PID passed in -- will not auto‐exit";
    }

    // 2) 如果拿到了有效 PID,则启动定时器监视
    if (hostPid > 0) {
        QTimer *watcher = new QTimer(&app);
        QObject::connect(watcher, &QTimer::timeout, [hostPid]() {
#ifdef Q_OS_WINDOWS
            // 尝试以 SYNCHRONIZE 权限打开父进程
            HANDLE h = OpenProcess(SYNCHRONIZE, FALSE, DWORD(hostPid));
            if (!h) {
                // 打开失败(进程不存在或无权限)
                qDebug() << "Host process gone or inaccessible. Exiting.";
                QCoreApplication::exit(0);
                return;
            }
            // 立即检查:如果对象已被 signaled,说明进程结束
            DWORD status = WaitForSingleObject(h, 0);
            CloseHandle(h);
            if (status == WAIT_OBJECT_0) {
                qDebug() << "Host process has exited. Exiting.";
                QCoreApplication::exit(0);
            }
#else
            // 在非 Windows 平台,可以用 kill(pid, 0) 或 /proc 检查
            if (::kill(hostPid, 0) != 0) {
                qDebug() << "Host process gone. Exiting.";
                QCoreApplication::exit(0);
            }
#endif
        });
        watcher->start(1000);  // 每秒检查一次
    }

    // 3) 主窗口或其他逻辑
    // MainWindow w;  
    // w.show();

    return app.exec();
}

关键点说明

打开进程句柄:Windows 下调用 OpenProcess(SYNCHRONIZE, FALSE, pid),只能获取一个"等待对象"句柄,不带任何写/读权限。

检测进程结束:WaitForSingleObject(handle, 0) 立即返回;若返回 WAIT_OBJECT_0,说明进程已退出。

清理:用完 HANDLE 一定要 CloseHandle()。

跨平台:在 Linux/macOS 下,通常用 kill(pid, 0) 或检查 /proc/ 是否存在。

这样,UI_Core.exe 就能在宿主进程意外退出或被正常关闭时,自己检测到并自动退出,保证不会在后台孤儿运行。

相关推荐
pumpkin845141 小时前
Rust Mock 工具
开发语言·rust
love530love1 小时前
【笔记】在 MSYS2(MINGW64)中安装 python-maturin 的记录
运维·开发语言·人工智能·windows·笔记·python
阿卡蒂奥2 小时前
C# 结合PaddleOCRSharp搭建Http网络服务
开发语言·http·c#
泉飒4 小时前
lua注意事项
开发语言·笔记·lua
hao_wujing4 小时前
使用逆强化学习对网络攻击者的行为偏好进行建模
开发语言·网络·php
还是鼠鼠4 小时前
单元测试-概述&入门
java·开发语言·后端·单元测试·log4j·maven
明月看潮生5 小时前
青少年编程与数学 02-020 C#程序设计基础 14课题、程序调试
开发语言·青少年编程·c#·编程与数学
cykaw25906 小时前
QT-JSON
qt·json
抽风的雨6106 小时前
【python深度学习】Day 42 Grad-CAM与Hook函数
开发语言·python·深度学习
Mikhail_G6 小时前
Python应用for循环临时变量作用域
大数据·运维·开发语言·python·数据分析