当前访客身份:游客 [ 登录 | 加入 OSCHINA ]

代码分享

当前位置:
代码分享 » C/C++  » Windows编程
sunooming

简单的win32服务程序框架

sunooming 发布于 2014年03月14日 13时, 0评/1687阅
分享到: 
收藏 +0
2
c++编写的win32服务程序
标签: Windows

代码片段(1) [全屏查看所有代码]

1. [文件] service.cpp ~ 2KB     下载(57)     跳至 [1] [全屏预览]

#include <windows.h>

//全局变量
SERVICE_STATUS g_service_status;
SERVICE_STATUS_HANDLE g_hservice_status;
bool g_is_running = true;

//函数声明
void WINAPI ServiceMain(DWORD argc, LPTSTR *argv);
void WINAPI ServiceCtrlHandler(DWORD Opcode);
void task(int argc,char* argv[]);

int main(int argc, char* argv[])
{
    SERVICE_TABLE_ENTRY DispatchTable[]={
										{"service",ServiceMain},		//服务函数入口地址
										{NULL,NULL}
						};
    StartServiceCtrlDispatcher(DispatchTable);
    return 0;
}

void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)                       //服务函数
{

    g_service_status.dwServiceType              = SERVICE_WIN32;        //WIN32服务
    g_service_status.dwCurrentState             = SERVICE_START_PENDING;
    g_service_status.dwControlsAccepted         = SERVICE_ACCEPT_STOP;
    g_service_status.dwWin32ExitCode            = 0;
    g_service_status.dwServiceSpecificExitCode  = 0;
    g_service_status.dwCheckPoint               = 0;
    g_service_status.dwWaitHint                 = 0;

    g_hservice_status = RegisterServiceCtrlHandler("service",ServiceCtrlHandler);
    if (g_hservice_status == (SERVICE_STATUS_HANDLE)0)
    {
        return;
    }
    g_service_status.dwCurrentState         = SERVICE_RUNNING;
    g_service_status.dwCheckPoint           = 0;
    g_service_status.dwWaitHint             = 0;
	SetServiceStatus (g_hservice_status,&g_service_status);

    g_is_running=true;
    while(g_is_running)
    {
        Sleep(1000);
        task( argc, argv);
    }
}

void task(int argc,char* argv[])								//录音主程序
{

}

void WINAPI ServiceCtrlHandler(DWORD Opcode)        //接受控制消息
{
    switch(Opcode)
    {
		case SERVICE_CONTROL_SHUTDOWN		:       //关机控制服务

		case SERVICE_CONTROL_STOP			:       //停止控制服务
			{
				g_service_status.dwWin32ExitCode = 0;
				g_service_status.dwCurrentState    = SERVICE_STOPPED;
				g_service_status.dwCheckPoint      = 0;
				g_service_status.dwWaitHint        = 0;
				SetServiceStatus (g_hservice_status,&g_service_status);
				g_is_running=false;
			}
			break;
		default:
			break;
    }
}


开源中国-程序员在线工具:Git代码托管 API文档大全(120+) JS在线编辑演示 二维码 更多»

开源从代码分享开始 分享代码
sunooming的其它代码 全部(1)...