How to start exe from a windows service and stop the service when the exe process terminates?

I am a complete newbie to working with Windows services. I have a basic skeleton designed for a service, and currently I'm doing this:

protected override void OnStart(string[] args) { base.OnStart(args); Process.Start(@"someProcess.exe"); } 

just to run exe at the beginning of the program.

However, I would like the service to stop when the process started with exe. I am pretty sure that I need to make some kind of thread (I also start with a newbie), but I'm not sure about the general way how this works and how to stop the process from the inside. Could you help me with a common process for this (i.e., start a thread from OnStart, then what ...?)? Thank you

+6
multithreading c # windows-services
source share
3 answers

You can use BackgroundWorker for streaming, use Process.WaitForExit() to wait for the process to complete before the service stops.

You are correct that you need to perform some streaming processing, and most of the work on OnStart can lead to errors in that they do not start correctly from Windows when the service starts.

 protected override void OnStart(string[] args) { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerAsync(); } private void bw_DoWork(object sender, DoWorkEventArgs e) { Process p = new Process(); p.StartInfo = new ProcessStartInfo("file.exe"); p.Start(); p.WaitForExit(); base.Stop(); } 

Edit You can also move Process p to a member of the class and stop the process in OnStop to make sure that you can stop the service again if exe goes into haywire.

 protected override void OnStop() { p.Kill(); } 
+9
source share

For this you need to use the ServiceController , it has a Stop method. Make sure your service has the CanStop property set to true.

+2
source share

someProcess.exe must have someLogic to stop the calling service;)

Use the ServiceController class.

 // Toggle the Telnet service - // If it is started (running, paused, etc), stop the service. // If it is stopped, start the service. ServiceController sc = new ServiceController("Telnet"); Console.WriteLine("The Telnet service status is currently set to {0}", sc.Status.ToString()); if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) || (sc.Status.Equals(ServiceControllerStatus.StopPending))) { // Start the service if the current status is stopped. Console.WriteLine("Starting the Telnet service..."); sc.Start(); } else { // Stop the service if its status is not set to "Stopped". Console.WriteLine("Stopping the Telnet service..."); sc.Stop(); } // Refresh and display the current service status. sc.Refresh(); Console.WriteLine("The Telnet service status is now set to {0}.", sc.Status.ToString()); 

Code from the page above.

+1
source share

All Articles