Check if a services is installed using C

前端 未结 2 943
无人及你
无人及你 2021-01-25 07:21

I\'m writing a C application which creates a Windows service. I\'d like to check if the service is installed before trying to call the installation function, but I can\'t manage

2条回答
  •  佛祖请我去吃肉
    2021-01-25 08:09

    A possibility would be to always attempt to CreateService() and if failure query GetLastError() and check if it is equal to ERROR_SERVICE_EXISTS:

    SC_HANDLE service_handle = CreateService(...);
    if (0 == service_handle)
    {
        if (ERROR_SERVICE_EXISTS == GetLastError())
        {
            /* Handle service already exists. */
        }
        else
        {
            /* Handle failure. */
        }
    }
    

    This would require a slight change to your code from having two functions InstallService() and CheckService() to having one function (for example) EnsureServiceInstalled().

    Or, you could use the OpenService() function, which will fail with GetLastError() code of ERROR_SERVICE_DOES_NOT_EXIST:

    SC_HANDLE scm_handle = OpenSCManager(0, 0, GENERIC_READ);
    
    if (scm_handle)
    {
        SC_HANDLE service_handle = OpenService(scm_handle,
                                               "the-name-of-your-service",
                                               GENERIC_READ);
        if (!service_handle)
        {
            if (ERROR_SERVICE_DOES_NOT_EXIST != GetLastError())
            {
                fprintf(stderr,
                        "Failed to OpenService(): %d\n",
                        GetLastError());
            }
            else
            {
                /* Service does not exist. */
                fprintf(stderr, "Service does not exist.\n");
            }
        }
        else
        {
            fprintf(stderr, "Opened service.\n");
            CloseServiceHandle(service_handle);
        }
    
        CloseServiceHandle(scm_handle);
    }
    else
    {
        fprintf(stderr,
                "Failed to OpenSCManager(): %d\n",
                GetLastError());
    }
    

提交回复
热议问题