使用定时器监视当前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 就能在宿主进程意外退出或被正常关闭时,自己检测到并自动退出,保证不会在后台孤儿运行。

相关推荐
界面开发小八哥22 分钟前
界面组件DevExpress WPF中文教程:Grid - 如何检查节点?
ui·.net·wpf·界面控件·devexpress·ui开发
L_autinue_Star1 小时前
手写vector容器:C++模板实战指南(从0到1掌握泛型编程)
java·c语言·开发语言·c++·学习·stl
元气小嘉1 小时前
前端技术小结
开发语言·前端·javascript·vue.js·人工智能
励志的大鹰哥1 小时前
V少JS基础班之第七弹
开发语言·javascript·ecmascript
AI360labs_atyun2 小时前
Java在AI时代的演进与应用:一个务实的视角
java·开发语言·人工智能·科技·学习·ai
凤年徐3 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题
nbsaas-boot3 小时前
多租户架构下的多线程处理实践指南
java·开发语言·spring
无小道3 小时前
c++--typedef和#define的用法及区别
c语言·开发语言·汇编·c++
SoniaChen334 小时前
Rust基础-part2-变量和可变类型
开发语言·后端·rust
沙振宇4 小时前
【Qt 学习之路】Qt Android开发环境搭建:Ubuntu的Vmware虚拟机中的踩坑实录
android·qt·学习