Skip to content

Instantly share code, notes, and snippets.

@mmmunk
Created June 18, 2020 11:14
Show Gist options
  • Save mmmunk/0b0adbccb6b91e778e3a6c6b47908c9c to your computer and use it in GitHub Desktop.
Save mmmunk/0b0adbccb6b91e778e3a6c6b47908c9c to your computer and use it in GitHub Desktop.
Very basic Windows Service template in C
// Very basic Windows Service template - maybe not fully correct/complete but it works.
// x86_64-w64-mingw32-gcc -mwindows -municode -O2 -s -o TempLoggerService.exe TempLoggerService.c
// SC create TempLoggerService binpath="C:\Temp\TempLoggerService.exe"
// SC delete TempLoggerService
#include <windows.h>
#include <stdio.h>
#define SERVICE_NAME L"TempLoggerService"
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE ServiceStatusHandle;
//wchar_t TempFile[256];
char TempFile[256];
void WriteToLog(char *s) {
FILE *log;
log = fopen(TempFile, "a+");
if (log == NULL)
return;
fprintf(log, "%s\n", s);
fclose(log);
}
void ServiceControlHandler(DWORD control) {
switch (control) {
case SERVICE_CONTROL_PAUSE:
ServiceStatus.dwCurrentState = SERVICE_PAUSED;
break;
case SERVICE_CONTROL_CONTINUE:
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
break;
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
break;
}
SetServiceStatus(ServiceStatusHandle, &ServiceStatus);
}
void ServiceMain(DWORD argc, LPWSTR *argv) {
// Setup service
ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = NO_ERROR ;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
ServiceStatusHandle = RegisterServiceCtrlHandler(SERVICE_NAME, ServiceControlHandler);
if (ServiceStatusHandle == 0)
return;
if (SetServiceStatus(ServiceStatusHandle, &ServiceStatus) == 0)
return;
// Init service
TempFile[0] = 0;
//GetTempPath(wcslen(TempFile), TempFile);
//wcscat(TempFile, SERVICE_NAME L".log");
GetTempPathA(sizeof TempFile, TempFile); // C:\Windows\Temp for system-kontrolleret service
strcat(TempFile, "TempLogger.log");
// Service main loop
while (ServiceStatus.dwCurrentState != SERVICE_STOPPED) {
Sleep(5000);
if (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
WriteToLog("Hej");
}
}
int wWinMain(HINSTANCE instance, HINSTANCE previnstance, LPWSTR cmdline, int showcmd) {
SERVICE_TABLE_ENTRY StartTable[] = {{SERVICE_NAME, ServiceMain}, {NULL, NULL}};
StartServiceCtrlDispatcher(StartTable);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment