码迷,mamicode.com
首页 > 编程语言 > 详细

C语言实现Windows服务并进行安装部署

时间:2015-02-27 10:12:41      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:c   windows   

// service_test.cpp : 定义控制台应用程序的入口点。
//


#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(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;
}


//输出到日志文件
int WriteToLog(char * str)
{
FILE *log;
log =  fopen(LOGFILE,"a+");
if (log==NULL)
{
return -1;
}
fprintf(log,"%s\n",str);
fclose(log);
return 0;

}



程序运行生成service_test.exe ,用管理员身份进入到控制台,cd  C:\Windows\system32 然后利用sc.exe工具 sc create service_test binPath= D:\TEST\service_test.exe控制台中会打印出 CreateService 成功。此时进入服务管理手动开启服务


C语言实现Windows服务并进行安装部署

标签:c   windows   

原文地址:http://blog.csdn.net/zjt107/article/details/43963995

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!