0

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.

porton
  • 5,214
  • 11
  • 47
  • 95
  • 1
    There are lots of questions here. You should check WaitForSingleObject result value, it may return an error. Sleep is rarely a good idea since it depends on the timings, the machine and everything one cannot control, and is often a bad smell. Sleep infinite is worse as it can hang a thread/process. If you really want to use Sleep you should put it in a loop with small sleep values (until the total is more than something big like minutes). Also you shouldn't set SERVICE_STOPPED if your process has successfully started – Simon Mourier Aug 27 '23 at 06:53

0 Answers0