Service_test.cpp: Defines the entry point of the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#define SLEEP_TIME 5000
#define LOGFILE "D:\\test\\memstatuse.txt"
int WriteToLog (char *);
Service_status ServiceStatus;
Service_status_handle Hstaus;
void ServiceMain (int argc,char **argv);
void Controlhandler (DWORD request);
int Initservice ();
int _tmain (int argc, _tchar* argv[])
{
Service_table_entry servicetable[2];
Servicetable[0].lpservicename = L "Memorystatus";
Servicetable[0].lpserviceproc = (lpservice_main_function) ServiceMain;
Servicetable[1].lpservicename = NULL;
Servicetable[1].lpserviceproc = NULL;
StartServiceCtrlDispatcher (servicetable);
return 0;
}
void ServiceMain (int argc,char **argv)
{
BOOL BRet;
BRet = TRUE;
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;
Hstaus = RegisterServiceCtrlHandler (L "Memorystatus", (lphandler_function) controlhandler);
if (Hstaus = = (service_status_handle) 0)
{
Return
}
Servicestatus.dwcurrentstate = service_running;
SetServiceStatus (Hstaus,&servicestatus);
Char memory[256];
while (servicestatus.dwcurrentstate = = service_running)
{
GetCurrentDirectory ((LPWSTR) memory);
int result = WriteToLog (memory);
if (result)
{
Servicestatus.dwcurrentstate = service_stopped;
Servicestatus.dwwin32exitcode =-1;
SetServiceStatus (Hstaus,&servicestatus);
Return
}
Sleep (Sleep_time);
}
Return
}
void Controlhandler (DWORD request)
{
Switch (Request)
{
Case SERVICE_CONTROL_STOP:
WriteToLog ("Monitoring Stopped");
Servicestatus.dwwin32exitcode = 0;
Servicestatus.dwcurrentstate = service_stopped;
SetServiceStatus (Hstaus,&servicestatus);
Return
Case Service_control_shutdown:
WriteToLog ("Monitoring Stopped");
Servicestatus.dwwin32exitcode = 0;
Servicestatus.dwcurrentstate = service_stopped;
SetServiceStatus (Hstaus,&servicestatus);
Return
Default
Break
}
SetServiceStatus (Hstaus,&servicestatus);
Return
}
Output to log file
int WriteToLog (char * str)
{
FILE *log;
Log = fopen (LOGFILE, "A +");
if (log==null)
{
return-1;
}
fprintf (log, "%s\n", str);
fclose (log);
return 0;
}
The program runs the build Service_test.exe, enters the console with the administrator, CD C:\Windows\system32 then uses the Sc.exe tool SC create service_test binpath= D:\TEST\ Service_test.exe the console will print out CreateService success. Enter service management to manually open the service at this time
C language implements Windows services and installs the deployment