我有一个作为本地系统运行的 .net Windows 服务。我有另一个 .net 进程需要等待服务终止。该进程不知道服务名称,因此无法查询服务控制管理器。它确实知道服务进程 ID。我可以修改 Windows 服务和其他进程的源代码。
当我这样做时:
process = Process.GetProcessById(processId);
process.WaitForExit();
从其他进程,我得到:
System.ComponentModel.Win32Exception: Access is denied
Stack trace:
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.WaitForExit(Int32 milliseconds)
GetProcessHandle 调用 OpenProcess .显然目标进程应该允许 SYNCHRONIZE bit对于上述工作,理论上可以通过 SetSecurityInfo 设置从 Windows 服务。但是,除了调用多个 pinvoke 来提升、启用特权并最终更改安全性之外,在 .NET 中似乎没有一种简单的方法可以做到这一点。
我是否忽略了一种从用户进程等待另一个(系统)进程的简单方法?
最佳答案
如果您知道服务进程 ID,为什么不能获取服务名称并从进程中检查服务状态,如下所示?
Process process = Process.GetProcessById(1);
ServiceController windowsService = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName == process.ProcessName);
//Wait until the windows service stops running
while (windowsService.Status == ServiceControllerStatus.Running)
{
Thread.Sleep(1000);
}
关于c# - 如何等待用户进程的系统进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26379215/