简体   繁体   English

在c / c ++中更改Windows服务的状态

[英]change status of windows services in c/c++

How can i change current state of a windows service from a C/C++ program ?? 如何从C / C ++程序中更改Windows服务的当前状态?

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? 例如,Mysql作为服务运行,其当前状态为“已启动”...如何检查状态以及如何从ac / c ++程序更改其状态? like if I want to change its status from 'Started' to 'Stopped' - how can i do it in c/c++? 如果我想将其状态从“已启动”更改为“已停止” - 我该如何在c / c ++中执行此操作?

QueryServiceStatus can be used to determine the status of a service. QueryServiceStatus可用于确定服务的状态。

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). 甚至还有一个完整的Starting a Service示例(以及匹配的Stopping a Service代码)。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM