Search code examples
windowsservicescriptingnsis

Does Windows sc order queries in any fashion?


Services are being managed using an NSIS installer. On uninstallation those services are stopped using net stop, because it is synchronous, then flagged for deletion using sc delete, as they do not have to be deleted immediately/synchronously.

Now I am wondering about the installation process. The order of calls is such:

  1. net stop service1
  2. net stop service2
  3. sc config service1 depend=dependency1
  4. sc config service2 depend=dependency2
  5. sc start service1
  6. sc start service2

Is there an intrinsic order to queries passed to sc? Are they worked through in the order sc is called (I assume they are not)? Are they being delegated to the respective service and queued there (this is what I hope for), e.g. whether service1 or service2 is stopped and configured first is ambiguous, but the sc config, sc start order is not? Is the order entirely ambiguous?

In addition I am curious to know what happens when mixing net and sc calls. Assume the following order:

  1. net stop service
  2. sc config service
  3. net start service

Is it reasonable to assume that the service would likely be stopped, then started before any configuration occurred?

Supposedly the general question is, how to ensure proper service setup via concatenated sc/net calls. The required order:

  1. Stop service (it may or may not exist on system)
  2. Create service / conffigure service
  3. Start service

Uninstallation is less pressing, because stopping services and flagging them for deletion is sufficient.


Solution

  • Mixing sc and net calls should not be a problem because it is the SCM (Service Control Manager) process that controls the services, other applications simply asks the SCM to perform a specific operation.

    The documentation for the ChangeServiceConfig API function states that:

    If the configuration is changed for a service that is running, with the exception of lpDisplayName, the changes do not take effect until the service is stopped.

    This leads me to believe that a installer can use the following sequence:

    Install/Configure --> Stop (synchronous) --> Start.

    Performing "Stop --> Configure --> Start" is always going to have a race condition issue because another process might trigger a service start at the wrong time.