Automatic delay start for services in C++

2019-08-08 17:41发布

问题:

I am trying to create a service that runs an executable file, .exe. The problem is that the service is not starting the .exe, everytime I reboot. It lacks consistency. But when I manually set the startup type to Automatic (Delayed start) it works perfectly. How can I set this startup type to Automatic (Delayed start) via C++?

This is the code I use to start automatically:

How should I change that "Service_auto_start" to Automatic (Delayed start)?

SC_HANDLE schService = CreateService
(
    schSCManager,                   /* SCManager database      */
    pName,                          /* Name of service         */
    pName,                          /* Service name to display */
    SERVICE_ALL_ACCESS,             /* Desired access          */
    SERVICE_WIN32_OWN_PROCESS|
      SERVICE_INTERACTIVE_PROCESS , /* Service type            */
    SERVICE_AUTO_START,             /* Start type              */
    SERVICE_ERROR_NORMAL,           /* Error control type      */
    pPath,                          /* Service's binary        */
    NULL,                           /* No load ordering group  */
    NULL,                           /* No tag identifier       */
    NULL,                           /* No dependencies         */
    NULL,                           /* LocalSystem account     */
    NULL
);

回答1:

the ChangeServiceConfig2 function can do this.

BOOL WINAPI ChangeServiceConfig2(
  __in          SC_HANDLE hService,
  __in          DWORD dwInfoLevel,
  __in          LPVOID lpInfo
);

set dwInfoLevel to SERVICE_CONFIG_DELAYED_AUTO_START_INFO to modify the start type to Delayed Auto start.

Note that this value is not supported on Windows Server 2003 and Windows XP. Also, this only dives description rather than delaying the service startup



回答2:

You should use the MsiServiceConfig Table available in Windows Installer 5.0 and later.

This means the functionality is only available in Windows 7/8 and Server 2008R2/2012. Does that fit your story? If so, read on. Otherwise an alternative might be to author a registry value in your MSI (DelayedAutoStart DWORD = 1 ).

You don't mention what authoring tool you are using to make your MSI. If the tool doesn't expose this underlying functionality, you should switch tools to one that does. Custom actions are a poor substitute for standard actions.