Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically restart a Windows Service

I know this can be done in C#/.Net but I was wondering whether it can be done calling the Windows API?

I have a service which will service DHCP requests, when I want to update the configuration for the service I need to stop the service, rewrite its INI file and then start the service again.

Any help appreciated!

like image 918
Nick Avatar asked May 25 '11 14:05

Nick


People also ask

How do I restart a Windows service itself?

Best way to have a Windows service restart itself is to set up two things: 1) Go to Services and look at the properties of your installed service. Go to Recovery and set the First Failure pick list to "Restart the Service". Set the Reset fail count after text box to 0 if you want to be able to restart it multiple times in a day.

How do I schedule a restart of my service?

I would use the Windows Scheduler to schedule a restart of your service. The problem is that you can't restart yourself, but you can stop yourself. (You've essentially sawed off the branch that you're sitting on... if you get my analogy) You need a separate process to do it for you. The Windows Scheduler is an appropriate one.

How to restart a Windows service multiple times in a day?

Set the Reset fail count after text box to 0 if you want to be able to restart it multiple times in a day. Set the Restart service after text box to how long you want to wait. Now if your service fails for whatever reason, it will try to restart. 2) Next in your Windows service, you set it to fail.

How to force a service to restart after failure?

You can set a service to restart after failure. So a restart can be forced by throwing an exception. Use recovery tab on service properties. Be sure to use reset fail count property to prevent service stopping altogether.


1 Answers

  1. Open the service control manager with OpenSCManager.
  2. Open the service you want to control with OpenService.
  3. Use ControlService or ControlServiceEx with a SERVICE_CONTROL_STOP parameter to stop the service.
  4. Do whatever you need to do.
  5. Use StartService to restart the service.
  6. Use CloseServiceHandle to close the service and SCM handles.
like image 152
Ferruccio Avatar answered Sep 17 '22 05:09

Ferruccio