如何等到 Windows 进程及其子进程全部退出?
我们有一个启动器应用程序,它执行一些设置(启动服务器),启动子进程,等待(通过工作线程)子进程退出,然后执行一些清理(停止服务器)。这已经就位并且运行良好。
但是,我们的某些应用程序可以启动其他应用程序。例如,启动器可能会启动应用程序 A,然后我可能会单击应用程序 A 中启动应用程序 B 的按钮。然后我关闭应用程序 A,启动器的 Process.WaitForExit 调用返回,启动器会停止服务器 - 却没有意识到应用程序 B 仍在运行。我们仅使用启动器进行开发测试,因此这不是危机,但当应用程序 B 尝试与服务器通信并崩溃时会很不方便。
启动子进程然后等待它(及其任何子进程)退出的最佳方法是什么?
这些应用程序(启动器和正在启动的应用程序)都在 .NET 中。如果我必须在每个应用程序中编写特殊代码(例如打开命名信号量)才能完成这项工作,那也没关系;我只是不确定最好的方法。
如果有某种方法可以只等待我的应用程序完成,例如,如果我的应用程序启动记事本,我就不想等待记事本关闭;我只想等待需要服务器的应用程序。但这不是一个要求,只是一个美好的愿望。
We have a launcher app that does some setup (starting a server), launches a child process, waits (via a worker thread) for the child process to exit, and then does some cleanup (stopping the server). This is already in place and works fine.
However, some of our apps can launch other apps. So for example, the launcher might start app A, and then I might click a button in app A that starts app B. Then I close app A, the launcher's Process.WaitForExit call returns, and the launcher stops the server -- unaware that app B is still running. We only use the launcher for development testing, so this isn't a crisis, but it's inconvenient when app B tries to talk to the server and crashes.
What's the best way to start a child process, and then wait for it (and any of its children) to exit?
These apps (both the launcher and the apps being launched) are all in .NET. It's fine if I have to write special code (e.g. opening a named semaphore) in each app to make this work; I'm just not sure of the best way to do it.
Bonus points if there's some way to only wait for my apps to finish -- e.g., if my app launches Notepad, I don't want to wait for Notepad to close; I just want to wait on apps that need the server. But this isn't a requirement, just a nicety.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在启动器应用程序中更改服务器关闭的条件。仅当您的进程名称均未运行时才关闭服务器。您可以定期检查进程名称。如果没有找到,则关闭服务器。
Change the condition of the server shutting down in the launcher app. Only shutdown the server, if none of your process names are running. You can periodically check for your process names. Shutdown the server if none found.
实际上,最简单的方法是让父进程等待其子进程,然后像您正在做的那样等待父进程。您可以通过这种方式准确选择等待哪些。
Actually, the easiest way to do this is to have the parent process wait for its child process(es), and then just wait for the parent process as you are doing. You can choose exactly which ones to wait for that way.