Reputation: 25799
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!
Upvotes: 16
Views: 27226
Reputation: 6471
Sometimes you want to restart the service from the service itself. This solution worked for me. I omitted the rather trivial timer code for clarity. Note that this solution works only because the caller is a service and runs at an elevated level.
void Watchdog::OnTimeout()
{
STARTUPINFO si = { };
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
PROCESS_INFORMATION pi = { };
// is modified by the call to CreateProcess (unicode version).
TCHAR szCmdLine[] = _T("cmd.exe /C \"net stop <yourservicenamehere> & net start <yourservicenamehere>\"");
// send shell command to restart our service.
if (!CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
{
// do some error reporting...
LOG("*** ERROR *** Watchdog timeout. Restart attempt failed. Last error: 0x%x\n", GetLastError());
}
}
Upvotes: 5
Reputation: 1133
I'm late for the party, but I'd suggest the official detailed examples for both starting and stopping a service. The advantage over the other answers here is that they include error handling, edge cases and dependent services -
Stop: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686335(v=vs.85).aspx Start: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686315(v=vs.85).aspx
Upvotes: 4
Reputation: 100658
Upvotes: 35
Reputation: 71525
You can also use WMI for this. The sample code at that link is VB, but it should be pretty easy to port to just about any language on Windows.
If you are into automation on Windows, WMI is good to learn because it provides a language-neutral object-oriented interface to most of the interesting objects on the system.
Upvotes: 2
Reputation: 3941
You'll need to open the service control manager (OpenSCManager), then open the service itself (OpenService) and finally ask it to start itself (StartService). Close off all the handles you've used along the way, then you're done.
Wow, handling services in C++ really takes me back...
Good luck,
Upvotes: 3
Reputation: 2686
Are you looking for something like this: Starting and stopping services ?
Upvotes: 3
Reputation:
Sure, there's a whole bunch of C API functions see for example http://msdn.microsoft.com/en-us/library/ms682108%28v=vs.85%29.aspx.
Upvotes: 5
Reputation: 6472
In a dos box, net start [service]
would do what you need. If you don't find an API solution, you could always start a process for net.exe
using start [service]
as parameters.
Upvotes: 2