Reputation: 2738
I am creating a Windows service that works hand in hand with other applications. These applications start communication with the service VIA Remoting. Once the connection has been made, I want to applications to stop communication immediately if the service is stopped. Meaning I don't want to wait for a Timer to elapse or have an exception because the communication was trying to use IpcConnection that is no longer valid.
This all works when the service is running Interactively instead of as a service. When it runs as a service then I get an exception. The service runs as Admin whether it is ran as a service or Interactively. If I run the other application as Admin, then it works as expected. Unfortunately, running this application as Admin will not be an option in production.
I've narrowed it down to what is causing the exception.
var serverProc = Process.GetProcessById(_remote.ProcessId);
serverProc.WaitForExit();
serverProc
is successful, but WaitForExit
fails.
System.ComponentModel.Win32Exception (0x80004005): Access is denied
at System.Diagnostics.ProcessManager.OpenProcess(Int32 processId, Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.WaitForExit(Int32 milliseconds)
I can substitute this code with a Timer
, but I was hoping this current technique would work.
Am I doing something work and is there something I can do to avoid the exception and use similar code?
Upvotes: 0
Views: 1117
Reputation:
It's highly likely that your services are running as a different user (probably LocalSystem). It's also highly likely that your application is running as your current user, not as an Administrator.
Non-administrator processes are not allowed to query some aspects of processes by other users. You can try running your application as administrator to verify that's your problem: try right clicking on your executable and choosing "Run as Administator", which would prompt the User Access Control dialog, and then should work without issue.
Assuming that works, you can use this question to make your application always require that permission: How do I force my .NET application to run as administrator?
Upvotes: 1