使用定時器監視當前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
#include <QCoreApplication>
#include <QProcess>int main(int argc, char *argv[])
{QCoreApplication app(argc, argv);// 1) 獲取宿主程序自身 PIDqint64 hostPid = QCoreApplication::applicationPid();// 2) 構造參數列表,將 hostPid 作為第一個參數傳給 UI_Core.exeQStringList 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 并監視宿主進程
#include <QApplication> // 或 QCoreApplication
#include <QTimer>
#include <QDebug>
#ifdef Q_OS_WINDOWS
# include <windows.h>
#endifint main(int argc, char *argv[])
{QApplication app(argc, argv);// 1) 解析命令行參數:arg1 應是宿主程序 PIDqint64 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 就能在宿主進程意外退出或被正常關閉時,自己檢測到并自動退出,保證不會在后臺孤兒運行。