Start & Stop a Windows Service from another Window

2019-09-18 20:09发布

I need to control a Windows service (slave) from another one (master) on the same machine (Windows 7 or Server 2008). It's unable to either start or stop the service. What do I need to do to be control the service? The master service is written in C#

UPDATE: The master service is meant to be a sort of watchdog - it monitors an HTTP connection to the slave and restarts the slave if the slave is non-responsive (not returning any HTTP data).

2条回答
等我变得足够好
2楼-- · 2019-09-18 20:30

You can have the master service create a new process that creates a hidden command window with an argument that causes it to call the windows command and start or stop the service. We use this model all the time at my job, the /C will cause the command window to exit as soon as the service finishes changing state.

System.Diagnostics.Process p = new System.Diagnostics.Process ();
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo ( "cmd.exe", "/C net [start or stop] [service name]");
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo = psi;
P.Start();

You will need to replace the bracketed sections of the command, and sorry if there are any syntax errors I am typing this on my tablet.

查看更多
我想做一个坏孩纸
3楼-- · 2019-09-18 20:38

The best way to handle windows services is to use System.ServiceProcess namespace. Check it on: https://ourcodeworld.com/articles/read/363/how-to-start-stop-and-verify-if-a-service-exists-with-c-in-winforms

But you will have some problems trying that because you will need administrator permissions to turn other services off, so you can handle that by following this link (for debug purposes you can open your VS as admin and everything will work):

How do I force my .NET application to run as administrator?

查看更多
登录 后发表回答