This example illustrates using SQLSCMGetLocalServiceState to query the execution state of the Microsoft® SQL Server™ service (MSSQLServer). The example illustrates branching based on the return value, using SQLSCMLocalServiceControl to start a stopped service, continue a paused service, or pause a running service.
LPSTR szService = "MSSQLServer";
DWORD dwServiceState;
DWORD dwErr;
BOOL bControlSuccessful;
// Query service state.
dwServiceState =
SQLSCMGetLocalServiceState(szService, &dwErr);
switch (dwServiceState)
{
case SERVICE_RUNNING: // Running, pause service.
{
bControlSuccessful =
SQLSCMLocalServiceControl(szService, SQLSCMCmd_PAUSE,
&dwErr, 0, NULL);
}
break;
case SERVICE_PAUSED: // Paused, so continue.
{
bControlSuccessful =
SQLSCMLocalServiceControl(szService, SQLSCMCmd_CONTINUE,
&dwErr, 0, NULL);
}
break;
case SERVICE_STOPPED: // Stopped, start service.
{
bControlSuccessful =
SQLSCMLocalServiceControl(szService, SQLSCMCmd_START,
&dwErr, 0, NULL);
}
break;
default:// Error or service is changing state.
{
if (dwServiceState)
{
// Service is changing state. Report current state
// and return success.
printf("Service execution state is %lu.\n", dwServiceState);
return (0);
}
else
{
// Error. Return failure.
printf("Error %lu on attempt to determine service state.\n",
dwErr);
return (1);
}
}
}
if (!bControlSuccessful)
{
printf("Error %lu returned on attempt to change service state.",
dwErr);
}
return (bControlSuccessful ? 0 : 1);