Windows下编写系统服务程序的实例

Windows下编写系统服务程序实例,在 VS2008 下编译测试通过。

代码如下:

#include <windows.h>
#include <stdio.h>
#include <time.h>


#define SLEEP_TIME 3000
#define LOGFILE "E:\\test.txt"
#define SERVICENAME "testNTService"


SERVICE_STATUS g_ServiceStatus; 
SERVICE_STATUS_HANDLE g_hStatus;


int WriteLog(const char* str)
{
	FILE* log;

	log = fopen(LOGFILE, "a+");

	if (log == NULL)
		return -1;

	fprintf(log, "%s\n", str);

	fclose(log);

	return 0;
}


void ControlHandler(DWORD request) 
{ 
	switch(request) 
	{ 
	case SERVICE_CONTROL_PAUSE:
		WriteLog("Pause.");
		g_ServiceStatus.dwWin32ExitCode = 0; 
		g_ServiceStatus.dwCurrentState = SERVICE_PAUSED;
		break;
	case SERVICE_CONTROL_CONTINUE:
		WriteLog("Continue.");
		g_ServiceStatus.dwWin32ExitCode = 0; 
		g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
		break;
	case SERVICE_CONTROL_STOP: 
		WriteLog("Stop.");
		g_ServiceStatus.dwWin32ExitCode = 0; 
		g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
		break;
	case SERVICE_CONTROL_SHUTDOWN: 
		WriteLog("Shutdown.");
		g_ServiceStatus.dwWin32ExitCode = 0; 
		g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
		break;
	default:
		break;
	} 

	SetServiceStatus (g_hStatus, &g_ServiceStatus);

	return; 
}



void ServiceMain(int argc, char** argv) 
{ 
	g_ServiceStatus.dwServiceType =    SERVICE_WIN32; 
	g_ServiceStatus.dwCurrentState =    SERVICE_START_PENDING; 
	g_ServiceStatus.dwControlsAccepted   =     SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
	g_ServiceStatus.dwWin32ExitCode = 0; 
	g_ServiceStatus.dwServiceSpecificExitCode = 0; 
	g_ServiceStatus.dwCheckPoint = 0; 
	g_ServiceStatus.dwWaitHint = 0; 

	g_hStatus = RegisterServiceCtrlHandler(SERVICENAME, (LPHANDLER_FUNCTION)ControlHandler); 
	if (g_hStatus == (SERVICE_STATUS_HANDLE)0) 
	{ 
		return; 
	}

	g_ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
	SetServiceStatus (g_hStatus, &g_ServiceStatus);

	char buf[256];
	time_t ltime;

	while(1)
	{
		if(g_ServiceStatus.dwCurrentState == SERVICE_RUNNING)
		{

			time( &ltime );
			ctime_s( buf, sizeof(buf), &ltime );

			if( WriteLog(buf) )
			{
				g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; 
				g_ServiceStatus.dwWin32ExitCode = -1; 
				SetServiceStatus(g_hStatus, &g_ServiceStatus);
				return;
			}
		}else if(g_ServiceStatus.dwCurrentState != SERVICE_PAUSED)
		{
			break;
		}

		Sleep(SLEEP_TIME);
	}

	return; 
}



int main() 
{ 
	SERVICE_TABLE_ENTRY ServiceTable[2];
	ServiceTable[0].lpServiceName = SERVICENAME;
	ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

	ServiceTable[1].lpServiceName = NULL;
	ServiceTable[1].lpServiceProc = NULL;

	StartServiceCtrlDispatcher(ServiceTable); 

	return 0;
}


编译出.exe文件后,用sc命令(参阅《在Windows系统下用命令把应用程序添加到系统服务》文章)把程序加入到服务中,然后就可以测试玩啦。

提示:如果编译时出现“无法从“const char [14]”转换为“LPWSTR””错误,打开工程的属性窗口,把 配置属性->常规->字符集 设置为“使用多字节字符集”后重新编译就好了。

你可能感兴趣的:(Windows下编写系统服务程序的实例)