如何启动分离进程并等待父进程终止?

How to start detached process and wait for the parent to terminate?

使用 QProcess 实现更新程序,我从我的应用程序启动一个分离进程并立即退出。在生成的更新程序进程中,我将根据需要覆盖文件,然后再次启动主应用程序。问题是,如果主应用程序在更新程序开始覆盖它们之前没有关闭 "fast enough" 以释放所有加载的库,文件更新有时会失败。一种方法是等待任意时间,如 1 秒,然后开始更新,但我宁愿实施一些实际检查父进程是否不再 运行 的东西。我可以在生成它时传递它的 ID,但这并没有真正削减它,因为似乎没有 bool QProcess::isRunning(qint64 pid) 等功能。我也不认为可以跨应用程序连接信号和插槽...有什么想法吗?

您可以在两个应用程序中使用 QSystemSemaphore class 等待。

应用程序:

int main()
{
  QSystemSemaphore sem( "some_uuid", 1, QSystemSemaphore::Create );
  sem.acquire();
  // ...
  app.exec();

  // TODO: start updater
  // sem.release(); // not sure, that it will not be done automatically
  return 0;
}

更新者:

int main()
{
  QSystemSemaphore sem( "some_uuid", 1, QSystemSemaphore::Open );
  sem.acquire(); // Will wait for application termination
  // ...
  app.exec();
  return 0;
}

你不应该忘记错误处理。您应该尝试以完全访问权限从 "updater.exe" 打开和关闭文件 "yourapp.exe",以确保该应用程序已关闭。

要获得 100% 的结果,最好使用特定于平台的 API。