Windows service does not catch shutdon event

Ramesh Deekonda 216 Reputation points
2021-02-25T15:14:44.103+00:00

I have created a windows service using the complete service sample provided by microsoft OneCodeTeam
I am not able to intercept the SHUTDOWN event on system shut down.A snippet of the code is as below:

  void WINAPI CServiceBase::ServiceCtrlHandler(DWORD dwCtrl)
  {
   extern void AddEntryLog(char*);
   switch (dwCtrl)
   {
   case SERVICE_CONTROL_STOP: s_service->Stop(); break;
   case SERVICE_CONTROL_PAUSE: s_service->Pause(); break;
   case SERVICE_CONTROL_CONTINUE: s_service->Continue(); break;
   case SERVICE_CONTROL_SHUTDOWN:AddEntryLog("shutdown event");    s_service->Shutdown(); break;
   case SERVICE_CONTROL_PRESHUTDOWN: s_service->PreShutDown(); break;
   case SERVICE_CONTROL_INTERROGATE: break;
   default: break;
   }
 }

The code AddEntryLog(msg) does not execute.

Your help is appreciated.

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,426 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,538 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 112.5K Reputation points
    2021-02-25T17:33:13.207+00:00

    According to documentation (https://learn.microsoft.com/en-us/windows/win32/services/service-control-handler-function), it seems that you must call SetServiceStatus with the SERVICE_ACCEPT_SHUTDOWN code on some stage. Then the service will receive SERVICE_CONTROL_SHUTDOWN.

    1 person found this answer helpful.

  2. Cheong00 3,471 Reputation points
    2021-03-01T01:29:49.53+00:00

    From your description of behaviour, you may also want to check whether "fast startup" is enabled in the target system.

    0 comments No comments