Stop-Service -Please

Stopping a Windows service is not about killing its process. It would be too brutal, unexpected and above all – a bit problematic in the case of shared services, having one process hosting more than one service. Killing a process would terminate all services, which is not the goal in most cases. Actually, stopping a service can be somewhat comparable to closing a window of a GUI application such as Notepad. It’s more about politely asking than about killing.

The service may say “no!” to such a request. It’s slightly more complicated than for a GUI app, as no window remains visible, but it’s possible and quite interesting inside. After the Service Manager (SCM) sends the stop request, a service sees it as SERVICE_CONTROL_STOP coming to the ServiceHandlerEx() function responsible for receiving orders.

The situation may be a bit more different when the stop request is a result of upcoming reboot. In such cases, a service receives SERVICE_CONTROL_PRESHUTDOWN letting it know why it’s time to terminate. Service should switch its state to SERVICE_STOP_PENDING meaning “ok, roger, will do that” and terminate as quickly as possible because someone (e.g. an end-user who clicked “reboot”) waits for it.

As services are important, the Service Manager has the power of delaying the real reboot until services terminate their jobs. And what if the service hangs? Probably the SCM should wait, but how long? The architecture of Windows provides a beautiful mechanism addressing such cases: each service must update dwWaitHint value, kind of a proof of life, increasing each time when queried. If the Service Manager sees the value stopped to increase, will kill the service mercilessly.

If the service keeps the Wait Hint updated, it clearly means it's alive and needs more time. In practice, this means we can create a service that never allows the reboot to happen. This is exactly what Windows Update does. It has something to do and will postpone rebooting as long as needed, not even providing an interface that allows the end user to disturb it.

And what if one wants to create such a service thinking it’s funny not to allow reboot ever to happen? Well… You can find it ready to use and/or analyze at https://github.com/gtworek/PSBits/tree/master/NoRebootSvc

Enjoy, and please, use it politely!