简体   繁体   English

从另一个Windows服务启动和停止Windows服务

[英]Start & Stop a Windows Service from another Windows Service

I need to control a Windows service (slave) from another one (master) on the same machine (Windows 7 or Server 2008). 我需要从同一台计算机(Windows 7或Server 2008)上的另一服务(主机)控制Windows服务(从机)。 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# 主服务是用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). 更新:主服务本来是一种看门狗-它监视与从服务器的HTTP连接,如果从服务器无响应(不返回任何HTTP数据),它将重新启动从服务器。

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. 您可以让主服务创建一个新进程,该进程将创建一个带有参数的隐藏命令窗口,该参数使其导致调用Windows命令并启动或停止该服务。 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. 我们一直在使用此模型,/ C将在服务完成状态更改后立即退出命令窗口。

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. 您将需要替换命令括号中的部分,如果我在平板电脑上键入任何语法错误,请对不起。

The best way to handle windows services is to use System.ServiceProcess namespace. 处理Windows服务的最佳方法是使用System.ServiceProcess命名空间。 Check it on: https://ourcodeworld.com/articles/read/363/how-to-start-stop-and-verify-if-a-service-exists-with-c-in-winforms 在以下位置进行检查: 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): 但是尝试这样做会遇到一些问题,因为您将需要管理员权限才能关闭其他服务,因此您可以通过以下链接进行处理(出于调试目的,您可以以admin身份打开VS,一切都会正常进行):

How do I force my .NET application to run as administrator? 如何强制.NET应用程序以管理员身份运行?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM