C language for Windows Services and installation and deployment
// Service_test.cpp: defines the entry point of the console application.
//
# Include "stdafx. h"
# Include
# Include
# 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 (256, (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 the 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 service_test.exe and enters the console as an administrator. After using the SC .exe tool SC create service_test binPath = D: \ TEST \ service_test.exe, CreateService is successfully printed on the console. In this case, go to service management and manually enable the service.