C语言编写Windows服务进程[实例]

C语言编写Windows服务进程[实例]

#include <windows.h>
SERVICE_STATUS ServiceStatus; 
SERVICE_STATUS_HANDLE hStatus; 
void WINAPI ControlHandler(DWORD request)
{
	//响应服务控制台的消息 
	ServiceStatus.dwCurrentState = SERVICE_RUNNING;
	ServiceStatus.dwWin32ExitCode= 0;
	if(SERVICE_CONTROL_STOP==request)ServiceStatus.dwCurrentState=SERVICE_STOPPED;
    if(SERVICE_CONTROL_SHUTDOWN==request)ServiceStatus.dwCurrentState=SERVICE_STOPPED;
	
    SetServiceStatus(hStatus,&ServiceStatus);
	return;
}
void WINAPI ServiceMain(DWORD argc, char* argv[])
{	
    ServiceStatus.dwServiceType = SERVICE_WIN32;
    ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN|SERVICE_ACCEPT_STOP;	//接受两种服务控制台请求
    ServiceStatus.dwWin32ExitCode = 0;
	ServiceStatus.dwServiceSpecificExitCode = 0;
    ServiceStatus.dwCheckPoint = 0;
    ServiceStatus.dwWaitHint = 0;
    hStatus = RegisterServiceCtrlHandlerA("",ControlHandler);
    if(0==hStatus){
    	//注册服务失败 
        ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
		ServiceStatus.dwWin32ExitCode= -1; 
		SetServiceStatus(hStatus,&ServiceStatus); 
    }else{
    	ServiceStatus.dwCurrentState = SERVICE_RUNNING;
    	SetServiceStatus(hStatus,&ServiceStatus);
    }
/*
	运行到这里,服务注册完毕。这里放要执行的代码 
*/
/*
	主动退出进程的方法 
	ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
	ServiceStatus.dwWin32ExitCode= 0; 
	SetServiceStatus(hStatus,&ServiceStatus);//通知服务管理器结束进程 
*/
	return;//这里返回后,程序不会自动结束 
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{ 
	SERVICE_TABLE_ENTRYA ServiceTable[2];
    ServiceTable[0].lpServiceName = "";
    ServiceTable[0].lpServiceProc = ServiceMain;
    ServiceTable[1].lpServiceName = 0;
    ServiceTable[1].lpServiceProc = 0;

    StartServiceCtrlDispatcherA(ServiceTable); 
    return 0;//这里返回后,程序不会自动结束 
}

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值