'Detect if system is about to restart or shutdown in Windows Service C program
I want to know if it is possible to detect whether the system is shutting down or about to restart from Windows Service code.
In my Windows service:
- If system is going to restart, I want to perform some actions.
- If system is going to shutdown, I don't need to run any actions.
I am familiar with using Windows Pre-Shutown flag used for performing critical actiosn before shutdown. But I don't know any mechanism to know if system is about to restart or shutodwn.
The code to detect preshutdown event can be as follows:
#include <windows.h>
#include <WinBase.h>
#include <tchar.h>
#include <strsafe.h>
#define SVC_ERROR ((DWORD)0xC0020001L)
SERVICE_STATUS gSvcStatus = { 0 };
SERVICE_STATUS_HANDLE g_ServiceStatusHandle = NULL;
HANDLE g_ServiceStopEvent = INVALID_HANDLE_VALUE;
VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv);
DWORD WINAPI SvcCtrlHandler(DWORD dwCtrl, DWORD eventType, void *eventData, void *context);
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam);
#define SVCNAME _T("SampleService")
//
// Purpose:
// Logs messages to the event log
//
// Parameters:
// szFunction - name of function that failed
//
// Return value:
// None
//
// Remarks:
// The service must have an entry in the Application event log.
//
VOID SvcReportEvent(LPTSTR szFunction)
{
HANDLE hEventSource;
LPCTSTR lpszStrings[2];
TCHAR Buffer[80];
hEventSource = RegisterEventSource(NULL, SVCNAME);
if (NULL != hEventSource)
{
StringCchPrintf(Buffer, 80, TEXT("%s failed with %d"), szFunction, GetLastError());
lpszStrings[0] = SVCNAME;
lpszStrings[1] = Buffer;
ReportEvent(hEventSource, // event log handle
EVENTLOG_INFORMATION_TYPE, // event type
0, // event category
SVC_ERROR, // event identifier
NULL, // no security identifier
2, // size of lpszStrings array
0, // no binary data
lpszStrings, // array of strings
NULL); // no binary data
DeregisterEventSource(hEventSource);
}
}
int _tmain(int argc, TCHAR *argv[])
{
SvcReportEvent(_T("My Sample Service: Main: Entry"));
SERVICE_TABLE_ENTRY ServiceTable[] =
{
{SVCNAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
{NULL, NULL}
};
if (StartServiceCtrlDispatcher(ServiceTable) == FALSE)
{
SvcReportEvent(_T("My Sample Service: Main: StartServiceCtrlDispatcher returned error"));
return GetLastError();
}
SvcReportEvent(_T("My Sample Service: Main: Exit"));
return 0;
}
VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
{
DWORD Status = E_FAIL;
SvcReportEvent(_T("My Sample Service: ServiceMain: Entry"));
g_ServiceStatusHandle = RegisterServiceCtrlHandlerEx(
SVCNAME,
SvcCtrlHandler,
NULL);
if (g_ServiceStatusHandle == NULL)
{
SvcReportEvent(_T("My Sample Service: ServiceMain: RegisterServiceCtrlHandler returned error"));
goto EXIT;
}
// Tell the service controller we are starting
ZeroMemory(&gSvcStatus, sizeof(gSvcStatus));
gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
gSvcStatus.dwControlsAccepted = 0;
gSvcStatus.dwCurrentState = SERVICE_START_PENDING;
gSvcStatus.dwWin32ExitCode = 0;
gSvcStatus.dwServiceSpecificExitCode = 0;
gSvcStatus.dwCheckPoint = 0;
if (SetServiceStatus(g_ServiceStatusHandle, &gSvcStatus) == FALSE)
{
SvcReportEvent(_T("My Sample Service: ServiceMain: SetServiceStatus returned error"));
}
/*
* Perform tasks neccesary to start the service here
*/
SvcReportEvent(_T("My Sample Service: ServiceMain: Performing Service Start Operations"));
// Create stop event to wait on later.
g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (g_ServiceStopEvent == NULL)
{
SvcReportEvent(_T("My Sample Service: ServiceMain: CreateEvent(g_ServiceStopEvent) returned error"));
gSvcStatus.dwControlsAccepted = 0;
gSvcStatus.dwCurrentState = SERVICE_STOPPED;
gSvcStatus.dwWin32ExitCode = GetLastError();
gSvcStatus.dwCheckPoint = 1;
if (SetServiceStatus(g_ServiceStatusHandle, &gSvcStatus) == FALSE)
{
SvcReportEvent(_T("My Sample Service: ServiceMain: SetServiceStatus returned error"));
}
goto EXIT;
}
// Tell the service controller we are started
gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PRESHUTDOWN;
gSvcStatus.dwCurrentState = SERVICE_RUNNING;
gSvcStatus.dwWin32ExitCode = 0;
gSvcStatus.dwCheckPoint = 0;
if (SetServiceStatus(g_ServiceStatusHandle, &gSvcStatus) == FALSE)
{
SvcReportEvent(_T("My Sample Service: ServiceMain: SetServiceStatus returned error"));
}
// Start the thread that will perform the main task of the service
HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThread, NULL, 0, NULL);
SvcReportEvent(_T("My Sample Service: ServiceMain: Waiting for Worker Thread to complete"));
// Wait until our worker thread exits effectively signaling that the service needs to stop
WaitForSingleObject(hThread, INFINITE);
SvcReportEvent(_T("My Sample Service: ServiceMain: Worker Thread Stop Event signaled"));
/*
* Perform any cleanup tasks
*/
SvcReportEvent(_T("My Sample Service: ServiceMain: Performing Cleanup Operations"));
CloseHandle(g_ServiceStopEvent);
gSvcStatus.dwControlsAccepted = 0;
gSvcStatus.dwCurrentState = SERVICE_STOPPED;
gSvcStatus.dwWin32ExitCode = 0;
gSvcStatus.dwCheckPoint = 3;
if (SetServiceStatus(g_ServiceStatusHandle, &gSvcStatus) == FALSE)
{
SvcReportEvent(_T("My Sample Service: ServiceMain: SetServiceStatus returned error"));
}
EXIT:
SvcReportEvent(_T("My Sample Service: ServiceMain: Exit"));
return;
}
DWORD WINAPI SvcCtrlHandler(DWORD dwCtrl, DWORD eventType, void *eventData, void *context)
{
if (dwCtrl == SERVICE_CONTROL_STOP)
{
SvcReportEvent((LPTSTR)TEXT("In function SvcCtrlHandler in condition SERVICE_CONTROL_STOP"));
gSvcStatus.dwWin32ExitCode = 0;
gSvcStatus.dwCurrentState = SERVICE_STOPPED;
}
else if (dwCtrl == SERVICE_CONTROL_PRESHUTDOWN)
{
SvcReportEvent((LPTSTR)TEXT("In function SvcCtrlHandler in condition SERVICE_CONTROL_PRESHUTDOWN"));
gSvcStatus.dwWin32ExitCode = 0;
gSvcStatus.dwCurrentState = SERVICE_STOPPED;
}
SetServiceStatus(g_ServiceStatusHandle, &gSvcStatus);
return NO_ERROR;
}
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
{
SvcReportEvent(_T("My Sample Service: ServiceWorkerThread: Entry"));
// Periodically check if the service has been requested to stop
while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0)
{
/*
* Perform main service function here
*/
// Simulate some work by sleeping
for (size_t i = 0; i < 1000000; i++)
{
char sentence[] = "Hello World";
FILE *fptr;
fptr = fopen("C:\\test\\program.txt", "a");
if (fptr == NULL)
{
printf("Error!");
}
else
{
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
Sleep(3000);
}
}
SvcReportEvent(_T("My Sample Service: ServiceWorkerThread: Exit"));
return ERROR_SUCCESS;
}
I need help form Stack overflow community to modify this code so that I can perform different actions before restart & shutdown while stopping service.
Note: It will not help me to detect restart or shutdown after system comes up. It has to be know before the system restart / shutdown itself.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
