palmer
palmer

Reputation: 1

CreateService or StartService hangs on windows 7 x64

CreateService or StartService hangs on windows 7 x64 when i trying to use it to register new service from service. In service control manager my service, which i try to run, has status 'Starting'.

Code that try to create and run service:

SC_HANDLE hSCManager = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(!hSCManager)
    throw ::GetLastError();
SC_HANDLE hService = ::OpenService(hSCManager,
                                       TEXT("ProcessManager"),
                                       SERVICE_ALL_ACCESS);

if(!hService && ::GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST)
{
    hService = ::CreateService(hSCManager, TEXT("ProcessManager"),
        TEXT("ProcessManager"), SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER,
        SERVICE_DEMAND_START, SERVICE_ERROR_IGNORE, TEXT("C:\\processmanager.sys"),
        NULL, NULL, NULL, NULL, NULL);
}

if(!hService ||
    (!::StartService(hService, 0, NULL) && ::GetLastError() != ERROR_SERVICE_ALREADY_RUNNING))
{
    ::CloseServiceHandle(hSCManager);
    if(hService)
        ::CloseServiceHandle(hService);
    DWORD err = ::GetLastError();
    throw err;
}

Please help :)

Upvotes: 0

Views: 975

Answers (1)

Harry Johnston
Harry Johnston

Reputation: 36348

From the documentation for ServiceMain:

Do not attempt to start another service in the ServiceMain function.

and

The SCM locks the service control database during initialization, so if a service attempts to call StartService during initialization, the call will block. When the service reports to the SCM that it has successfully started, it can call StartService. If the service requires another service to be running, the service should set the required dependencies.

So, there's your problem: your program is deadlocking because it is calling StartService while the service control database is locked. (Actually, it is probably deadlocking on the CreateService call first; the documentation doesn't explicitly mention it, but the same restriction applies there too.)

Install the device driver at the same time that you install your service, rather than trying to install it from your service.

Upvotes: 2

Related Questions