#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define SLEEP_TIME 5000
#define FILE_PATH "c:\\log.txt"
BOOL bRunning;
void WINAPI ServiceMain(int argc,char** argv);
void WINAPI ServiceCtrlHandler(DWORD Opcode);
SERVICE_STATUS m_ServiceStatus;
SERVICE_STATUS_HANDLE m_ServiceStatusHandle;
int WriteToLog(char* str);
void main(void){
SERVICE_TABLE_ENTRY DispatchTable[2];
DispatchTable[0].lpServiceName="demo";
DispatchTable[0].lpServiceProc=(LPSERVICE_MAIN_FUNCTION)ServiceMain;
DispatchTable[1].lpServiceName=NULL;
DispatchTable[1].lpServiceProc=NULL;
StartServiceCtrlDispatcher(DispatchTable);//注册服务主函数
}
int WriteToLog(char* str){
FILE* pfile;
fopen_s(&pfile,FILE_PATH,"a+");
if(pfile==NULL){
return -1;
}
fprintf_s(pfile,"%s\n",str);
fclose(pfile);
return 0;
}
void WINAPI ServiceMain(int argc,char** argv){
MEMORYSTATUS memstatus;
char str[100];
int availmb;
m_ServiceStatus.dwServiceType=SERVICE_WIN32;
m_ServiceStatus.dwCurrentState=SERVICE_START_PENDING;
m_ServiceStatus.dwControlsAccepted=SERVICE_ACCEPT_SHUTDOWN|SERVICE_ACCEPT_STOP;
m_ServiceStatus.dwWin32ExitCode=0;
m_ServiceStatus.dwServiceSpecificExitCode=0;
m_ServiceStatus.dwCheckPoint=0;
m_ServiceStatus.dwWaitHint=0;
//注册服务控制函数
m_ServiceStatusHandle = RegisterServiceCtrlHandler("demo",ServiceCtrlHandler);
if(m_ServiceStatusHandle==0){
WriteToLog("写出失败日志");
return;
}
WriteToLog("写出成功日志");
m_ServiceStatus.dwCurrentState=SERVICE_RUNNING;
SetServiceStatus(m_ServiceStatusHandle,&m_ServiceStatus);
bRunning=TRUE;
memset(str,'\0',100);
while(bRunning){
GlobalMemoryStatus(&memstatus);
availmb=memstatus.dwAvailPhys/1024/1024;
sprintf_s(str,100,"可用内存的大小是%dMB",availmb);
WriteToLog(str);//每隔5秒写出执行日志
Sleep(SLEEP_TIME);
}
WriteToLog("服务停止写出日志");
}
void WINAPI ServiceCtrlHandler(DWORD Opcode){
switch(Opcode){
case SERVICE_CONTROL_STOP:
bRunning=FALSE;
m_ServiceStatus.dwCurrentState=SERVICE_STOPPED;
break;
case SERVICE_CONTROL_SHUTDOWN:
bRunning=FALSE;
m_ServiceStatus.dwCurrentState=SERVICE_STOPPED;
break;
default:
break;
}
SetServiceStatus(m_ServiceStatusHandle,&m_ServiceStatus);
}
生成后cmd执行sc命令安装服务
sc create demo3 binpath= c:\demo3.exe
启动服务后完美运行并写出日志
以上代码生成的可执行服务程序
|