Skip to content

Instantly share code, notes, and snippets.

@beginor
Last active October 20, 2021 05:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save beginor/6f8a6f46489bfd8e6dce to your computer and use it in GitHub Desktop.
Save beginor/6f8a6f46489bfd8e6dce to your computer and use it in GitHub Desktop.
Windows Service with c
#include <windows.h>
#include <stdio.h>
#define SLEEP_TIME 5000
#define LOGFILE "C:\\memstatus.txt"
int WriteToLog(char* str) {
FILE* log;
log = fopen(LOGFILE, "a+");
if (log == NULL)
return -1;
fprintf(log, "%s\n", str);
fclose(log);
return 0;
}
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE ServiceStatusHandle;
// Service initialization
int InitService() {
int result;
result = WriteToLog("Monitoring started.");
return(result);
}
// Control handler function
void ServiceControlHandler(DWORD request) {
switch (request) {
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
WriteToLog("Monitoring stopped.");
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
break;
default:
break;
}
// Report current status
SetServiceStatus(ServiceStatusHandle, &ServiceStatus);
return;
}
void ServiceMain(int argc, char** argv) {
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
ServiceStatusHandle = RegisterServiceCtrlHandler(
L"MemoryStatus",
(LPHANDLER_FUNCTION)ServiceControlHandler
);
if (ServiceStatusHandle == NULL) {
// Registering Control Handler failed
return;
}
// Initialize Service
int error = InitService();
if (error) {
// Initialization failed
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(ServiceStatusHandle, &ServiceStatus);
return;
}
// We report the running status to SCM.
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(ServiceStatusHandle, &ServiceStatus);
MEMORYSTATUS memory;
// The worker loop of a service
while (ServiceStatus.dwCurrentState == SERVICE_RUNNING) {
char buffer[16];
GlobalMemoryStatus(&memory);
sprintf(buffer, "%d", memory.dwAvailPhys);
int result = WriteToLog(buffer);
if (result) {
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(ServiceStatusHandle, &ServiceStatus);
return;
}
Sleep(SLEEP_TIME);
}
return;
}
int main(int argc, char** argv) {
SERVICE_TABLE_ENTRY entry;
entry.lpServiceName = L"MemoryStatus";
entry.lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
// Start the control dispatcher thread for our service
StartServiceCtrlDispatcher(&entry);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment