使用定时器监视当前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 也随之自动关闭 如何实现。
- 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(方便日志或做进一步管理),但这不是必须的。
- 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 就能在宿主进程意外退出或被正常关闭时,自己检测到并自动退出,保证不会在后台孤儿运行。