How to wait till a stop signal in Windows?

71 Views Asked by At

srvany-next is my open source command-line utility that allows to start another command-line utility as a Windows service:

srvany-next.exe "c:\bin\utility.exe" -arguments

The above is the command that starts utility.exe as a Windows service.

This is code from my open source utility srvany-next, old version:

    if (CreateProcess(global_argv[1], applicationParameters, NULL, NULL, FALSE, dwFlags, applicationEnvironment, applicationDirectory, &startupInfo, &g_Process))
    {
        ServiceSetState(SERVICE_ACCEPT_STOP, SERVICE_RUNNING, 0);
        HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThread, NULL, 0, NULL);
        if (hThread == NULL)
        {
            ServiceSetState(0, SERVICE_STOPPED, GetLastError());
            return;
        }
        WaitForSingleObject(hThread, INFINITE); //Wait here for a stop signal.
    }
    CloseHandle(g_ServiceStopEvent);
    ServiceSetState(0, SERVICE_STOPPED, 0);

and new version:

    if (CreateProcess(global_argv[1], applicationParameters, NULL, NULL, FALSE, dwFlags, applicationEnvironment, applicationDirectory, &startupInfo, &g_Process))
    {
        ServiceSetState(SERVICE_ACCEPT_STOP, SERVICE_RUNNING, 0);
        Sleep(INFINITE);
    }
    CloseHandle(g_ServiceStopEvent);
    ServiceSetState(0, SERVICE_STOPPED, 0);

Previously, it worked. But after changing the software that is launched by CreateProcess, WaitForSingleObject started to exit immediately (why?). I commented it out and replaces by Sleep. Now, when I start the service using Windows Services app, it appears to start; but I don't see log of my app (that is to be started by CreateProcess) and can't connect to it by HTTP; also GNU utility ps does not show it running. So, it appears that the app started by CreateProcess does not really start.

When I start it (without srvany-next, that is not as a service) from command line under admin account, it works.

Is using Sleep here correct? Don't we need to process process starting events? (if in Windows there are process starting events) I suspect that Sleep blocks processing of events and therefore CreateProcess is not fully executed. Or why else may it not work?

You have the full source and a welcome to contribute, as it is a useful Windows software.

0

There are 0 best solutions below