Home > Technology > 创建WINDOWS服务程序

创建WINDOWS服务程序

Sat, 13 Dec 2008 17:11:38 +0800
1.安装和删除服务
首先向服务控制管理器安装服务:

int install_service() { SC_HANDLE sc, sv; SERVICE_DESCRIPTION scsc; char str[MAX_PATH];
GetModuleFileName(NULL, str, MAX_PATH); scsc.lpDescription = "Service test"; sc = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (sc == NULL) { printf("Install service error."); return 0; }
strcat(str, " -runserver");
sv = CreateService(sc, "TestSrv", "Test service", SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,SERVICE_ERROR_IGNORE, str, NULL, NULL, NULL, NULL, NULL);
if (sv != NULL){ ChangeServiceConfig2(sv, SERVICE_CONFIG_DESCRIPTION, &scsc); CloseServiceHandle(sv); }else{ CloseServiceHandle(sc); }
printf("Service Installed"); return 0; }


删除服务为以下程序:

int delete_service()
{
SC_HANDLE sc, sv;
SERVICE_STATUS ss;
sc = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (sc == NULL) {
printf("OpenSCManage error.");
return 0;
}
sv = OpenService(sc, "TestSrv", SERVICE_ALL_ACCESS);
if (sv != NULL) {
QueryServiceStatus(sv, &ss);
if(ss.dwCurrentState != SERVICE_STOPPED)
ControlService(sv, SERVICE_CONTROL_STOP, &ss);
DeleteService(sv);
CloseServiceHandle(sv);
}
CloseServiceHandle(sc);
printf("Service Deleted");
return 0;
}


2.服务主线程程序和服务控制程序:

void WINAPI TestServiceMain(DWORD dwArgc, LPTSTR *lpszArgv)
{
SERVICE_STATUS_HANDLE hStatus;
SERVICE_STATUS ServiceStatus;
hStatus = RegisterServiceCtrlHandler("TestSrv",
(LPHANDLER_FUNCTION)ControlHandle);
if (hStatus == (SERVICE_STATUS_HANDLE)0) return;
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;
SetServiceStatus(hStatus, &ServiceStatus);
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(hStatus, &ServiceStatus);
/*开始*/
begin_session();
}

void ControlHandle(DWORD dwControl)
{
switch (dwControl) {
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
break;
}
}


3.从程序入口启动服务

int startup_service()
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = "TestSrv";
ServiceTable[0].lpServiceProc =
(LPSERVICE_MAIN_FUNCTION)TestServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
// 启动服务的控制分派机线程
StartServiceCtrlDispatcher(ServiceTable);
return 0;
}
Tag:WINDOWS
Hots
评论
发表评论:


  [TIPS:首次发表评论的朋友,需要验证]
Tags
Recent Post
Recent Comments
Links
Copyright Notes
You can reship all of these articles without permission but MUST mark the original link in your post. Please contact with me() if u have advice or other arrangements.
Copyright©2007-2011 lewphee.com All rights reserved.