// WinService2.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <stdio.h> SERVICE_STATUS ServiceStatus; SERVICE_STATUS_HANDLE hStatus; void WriteLog(char *str){ FILE *log; log =fopen("G://log.txt", "a+"); if (log ==NULL) printf("logfile init failed!"); fprintf(log,"%s ", str); fclose(log); } void InitService(){ WriteLog("Monitoring started."); }
/*用来识别服务命令的函数*/ void WINAPI ControlHandler(DWORD request) { switch(request) { case SERVICE_CONTROL_STOP: WriteLog("Monitoring stopped."); ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (hStatus, &ServiceStatus); return; case SERVICE_CONTROL_SHUTDOWN: WriteLog("Monitoring stopped."); ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (hStatus, &ServiceStatus); return; default: break; } SetServiceStatus (hStatus, &ServiceStatus); return; }
/*用来后台执行任务的主函数*/ void WINAPI ServiceMain(int argc, char** argv){ int error; ServiceStatus.dwServiceType = SERVICE_WIN32; ServiceStatus.dwCurrentState = SERVICE_START_PENDING; ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCheckPoint = 0; ServiceStatus.dwWaitHint = 0; hStatus = RegisterServiceCtrlHandler( L"logservice", ControlHandler); if (hStatus == (SERVICE_STATUS_HANDLE)0){ return; } InitService(); ServiceStatus.dwCurrentState = SERVICE_RUNNING; SetServiceStatus (hStatus, &ServiceStatus); while (ServiceStatus.dwCurrentState == SERVICE_RUNNING) { WriteLog("windows service"); Sleep(1000); } return; } void start(){ SERVICE_TABLE_ENTRY ServiceTable[2]; ServiceTable[0].lpServiceName = L"logservice"; ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain; ServiceTable[1].lpServiceName = NULL; ServiceTable[1].lpServiceProc = NULL; StartServiceCtrlDispatcher(ServiceTable); } int _tmain(int argc, _TCHAR* argv[]) { start(); return 0; }
编译成功后,直接使用命令sc create logservice binpath= [你编译成功后exe的文件]
注意binpath=后面与路径的空格