How can i change current state of a windows service from a C/C++ program ??
for example say, Mysql is running as a service and its current status is 'Started'... how can I check the status and how can i change its status from ac/c++ program? like if I want to change its status from 'Started' to 'Stopped' - how can i do it in c/c++?
QueryServiceStatus
can be used to determine the status of a service.
Look at the other Service functions to change the status. There is even a complete Starting a Service example (and the matching Stopping a Service code).
A small code snippet that should you get you started:
/* Open service control manager. */
SC_HANDLE scm_handle = OpenSCManager(0,
0,
SC_MANAGER_ALL_ACCESS);
/* Ensure (0 != scm_handle) */
/* Open service. */
SC_HANDLE service_handle = OpenService(scm_handle,
"mysql-service-name",
SERVICE_ALL_ACCESS);
/* Ensure (0 != service_handle) */
/* Try to stop the service if it is running. */
SERVICE_STATUS status; /* This may need populated differently for mysql. */
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
if (ControlService(service_handle, SERVICE_CONTROL_STOP, &status))
{
Sleep(1000);
while (QueryServiceStatus(service_handle, &status))
{
if(status.dwCurrentState == SERVICE_STOP_PENDING)
{
Sleep(1000);
}
else
{
break;
}
}
if (status.dwCurrentState == SERVICE_STOPPED)
{
/* Success: service stopped. */
}
else
{
/* Failure: service not stopped. */
}
}
else
{
/* Failed to issue stop request. */
}
CloseServiceHandle(service_handle);
CloseServiceHandle(scm_handle);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.