Windows系统服务创建步骤,常用类封装,废话不多说,直接上代码
// ServceDemo.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include "WindwosService.h" unsigned __stdcall SvcRun (void *Params )
{
while()
{ for (int i = ;i < ;i++)
{
printf("%d\n",i);
} ::Sleep(**);
}
return ;
} int _tmain(int argc, _TCHAR* argv[])
{
#ifdef WIN32
InitService(argc,argv);
#endif // WIN32 #ifdef linux #endif // linux return ;
}
main函数文件代码
#if !defined JX_About_Privilege
#define JX_About_Privilege #include <Windows.h>
// Windows提权类
class JXAboutPrivilege
{
public:
JXAboutPrivilege(void);
~JXAboutPrivilege(void);
// 提升关机权限
static BOOL EnableShutdownPrivileges( VOID );
// 提升结束进程的权限
static BOOL EnableTermProcessPrivileges( VOID );
// 提升加载驱动的权限
static BOOL EnableLoadDriverPrivileges( VOID ); static BOOL EnableDebugPrivilege(BOOL fEnable);
}; #endif
JXAboutPrivilege.h
#include "StdAfx.h"
#include "JXAboutPrivilege.h" JXAboutPrivilege::JXAboutPrivilege(void)
{
} JXAboutPrivilege::~JXAboutPrivilege(void)
{
} BOOL JXAboutPrivilege::EnableShutdownPrivileges( VOID )
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
BOOL Result = FALSE; if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
return FALSE; LookupPrivilegeValue( NULL, SE_SHUTDOWN_NAME, &(tkp.Privileges[].Luid) );
tkp.PrivilegeCount = ;
tkp.Privileges[].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, );
DWORD dwError = GetLastError();
if ( ERROR_SUCCESS == dwError )
Result = TRUE; CloseHandle( hToken );
return Result;
} BOOL JXAboutPrivilege::EnableTermProcessPrivileges( VOID )
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
BOOL Result = FALSE; if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
return FALSE; LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &(tkp.Privileges[].Luid) );
tkp.PrivilegeCount = ;
tkp.Privileges[].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, );
DWORD dwError = GetLastError();
if ( ERROR_SUCCESS == dwError )
Result = TRUE; CloseHandle( hToken );
return Result;
} BOOL JXAboutPrivilege::EnableLoadDriverPrivileges( VOID )
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
BOOL Result = FALSE; if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
return FALSE; LookupPrivilegeValue( NULL, SE_LOAD_DRIVER_NAME, &(tkp.Privileges[].Luid) );
tkp.PrivilegeCount = ;
tkp.Privileges[].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, );
DWORD dwError = GetLastError();
if ( ERROR_SUCCESS == dwError )
Result = TRUE; CloseHandle( hToken );
return Result;
} BOOL JXAboutPrivilege::EnableDebugPrivilege(BOOL fEnable)
{
BOOL fOk = FALSE; // Assume function fails
HANDLE hToken;
// Try to open this process's access token
if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
// Attempt to modify the "Debug" privilege
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = ;
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tp.Privileges[].Luid);
tp.Privileges[].Attributes = fEnable ? SE_PRIVILEGE_ENABLED : ;
AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
fOk = (GetLastError() == ERROR_SUCCESS);
CloseHandle(hToken);
}
return(fOk);
}
JXAboutPrivilege.cpp
#if !defined JX_Service_Control
#define JX_Service_Control
#include <Windows.h> // Windows服务控制类
class JXServiceControl
{
public:
JXServiceControl(void);
~JXServiceControl(void);
public:
int ChangeServicePath( );
int createService();
int deleteService();
void startService();
void stopService();
BOOL isSvsRuning();
BOOL isSvsExist();
//设置服务名
void SetServiceName(const char * str);
//设置服务管理面板显示名字
void SetServiceShowName(const char *str);
//设置服务EXE文件位置
void SetExePath(const char *str);
private:
//服务名
char sSname[MAX_PATH+];
//服务Caption
char sShowName[MAX_PATH+];
//服务可执行文件路径
char sSvcExePath[MAX_PATH+];
}; #endif
JXServiceControl.h
WindwosService.h
#include "WindwosService.h" SERVICE_STATUS ServiceStatus = {};
SERVICE_STATUS_HANDLE hStatus = NULL; void Run()
{
_beginthreadex(NULL, NULL, SvcRun, NULL, NULL, NULL);
} void WINAPI ControlHandler(DWORD fdwControl)
{
switch(fdwControl)
{
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
ServiceStatus.dwWin32ExitCode = ;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
default: break;
}
SetServiceStatus(hStatus, &ServiceStatus);
} void WINAPI ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{ ZeroMemory(&ServiceStatus, sizeof(ServiceStatus));
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;// 正在启动中...
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; hStatus = RegisterServiceCtrlHandler(SERVER_NAME, (LPHANDLER_FUNCTION)ControlHandler); // 注册当前服务的控制函数
if (!hStatus)
{
OutputDebugString(" RegisterServiceCtrlHandler 失败....\n");
return;
}
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(hStatus, &ServiceStatus);// 修改服务状态
//////////////////////下方为启动主线程/////////////////////////////////////////
Run();
//////////////////////////////////////////////////////////////////////////
while()
{
::Sleep();
}
//::WaitForSingleObject(hThread,INFINITE); // 等待线程结束
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -;
SetServiceStatus(hStatus, &ServiceStatus);
} int InitService(int argc, TCHAR* argv[])
{
JXAboutPrivilege::EnableDebugPrivilege(TRUE);
JXAboutPrivilege::EnableLoadDriverPrivileges();
JXAboutPrivilege::EnableShutdownPrivileges();
JXAboutPrivilege::EnableTermProcessPrivileges(); if (argc == )
{
if (!stricmp(argv[],("-install")))
{
// InstallServices();
return ;
}
if (!stricmp(argv[], ("-uninstall")))
{
// UnInstallServices();
return ;
}
if (!stricmp(argv[], ("-run")))
{
Run();
while (TRUE)
Sleep();
return ;
}
}
SERVICE_TABLE_ENTRY DispatchTable[] = {
{ SERVER_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain },
{ NULL, NULL }
}; StartServiceCtrlDispatcher(DispatchTable);
} void InstallServices()
{
TCHAR path_nor[MAX_PATH] = { };
GetModuleFileName(NULL, path_nor, MAX_PATH); JXServiceControl sc;
sc.SetExePath(path_nor);
sc.SetServiceName((SERVER_NAME));
sc.SetServiceShowName((SERVER_NAME)); if ( sc.isSvsExist() && sc.isSvsRuning() )
{
sc.stopService();
sc.ChangeServicePath();
}
else if ( sc.isSvsExist() )
{
sc.ChangeServicePath();
}
else if (!sc.isSvsExist())
{
sc.createService();
} sc.startService();
} void UnInstallServices()
{
TCHAR path_nor[MAX_PATH] = { };
GetModuleFileName(NULL, path_nor, MAX_PATH); JXServiceControl sc;
sc.SetExePath(path_nor);
sc.SetServiceName((SERVER_NAME));
sc.SetServiceShowName((SERVER_NAME)); if ( sc.isSvsExist() && sc.isSvsRuning() )
{
sc.stopService();
}
if( sc.isSvsExist() )
sc.deleteService();
}
WindwosService.cpp
#include "StdAfx.h"
#include "JXServiceControl.h" JXServiceControl::JXServiceControl(void)
{
memset(sSname,,MAX_PATH);
memset(sShowName,,MAX_PATH);
memset(sSvcExePath,,MAX_PATH);
} JXServiceControl::~JXServiceControl(void)
{ } int JXServiceControl::ChangeServicePath()
{
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
SC_HANDLE hsev = NULL;
if(scHandle != NULL)
{
hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
if(hsev != NULL)
{
BOOL bRet = ChangeServiceConfig(
hsev,
SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,
sSvcExePath,
NULL,
NULL,
NULL,
NULL,
NULL,
sShowName
);
CloseServiceHandle(hsev); }
else
{
CloseServiceHandle(scHandle);
return ;
}
CloseServiceHandle(scHandle);
}
else
return -; return ;
} int JXServiceControl::createService()
{
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE);
if (scHandle == NULL)
{
return -;
}
SC_HANDLE hsvc = CreateService(scHandle,sSname,sShowName,SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,sSvcExePath,
NULL,NULL,NULL,NULL,NULL);
if (hsvc != NULL)
{
CloseServiceHandle(hsvc);
}
else
{
return ;
}
CloseServiceHandle(scHandle);
return ;
} int JXServiceControl::deleteService()
{
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
SC_HANDLE hsev = NULL;
if(scHandle != NULL)
{
hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
SERVICE_STATUS mss;
if(hsev != NULL)
{
QueryServiceStatus(hsev,&mss);
if (mss.dwCurrentState != SERVICE_RUNNING)
{
ControlService(hsev,SERVICE_CONTROL_STOP,&mss);
DeleteService(hsev); }
CloseServiceHandle(hsev);
} else
{
CloseServiceHandle(scHandle);
return ;
}
CloseServiceHandle(scHandle);
}
else return -;
return ;
} void JXServiceControl::startService()
{
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
SC_HANDLE hscv = NULL;
if (scHandle != NULL)
{
hscv = OpenService(scHandle,sSname,SERVICE_START);
if(hscv != NULL)
{
BOOL isSucess = StartService(hscv,,NULL);
DWORD err = ;
if (isSucess == )
{
err = GetLastError();
}
CloseServiceHandle(hscv);
}
CloseServiceHandle(scHandle);
}
} void JXServiceControl::stopService()
{
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
SC_HANDLE hsev = NULL;
if(scHandle != NULL)
{
hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
SERVICE_STATUS mss;
if(hsev != NULL)
{
QueryServiceStatus(hsev,&mss);
if (mss.dwCurrentState == SERVICE_RUNNING)
{
ControlService(hsev,SERVICE_CONTROL_STOP,&mss);
CloseServiceHandle(hsev);
}
}
CloseServiceHandle(scHandle);
}
} BOOL JXServiceControl::isSvsRuning()
{
BOOL ret = FALSE;
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
SC_HANDLE hsev = NULL;
if(scHandle != NULL)
{
hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
SERVICE_STATUS mss;
if(hsev != NULL)
{
QueryServiceStatus(hsev,&mss);
if (mss.dwCurrentState == SERVICE_RUNNING)
{
ret = TRUE;
CloseServiceHandle(hsev);
} }
CloseServiceHandle(scHandle);
}
return ret;
} BOOL JXServiceControl::isSvsExist()
{
BOOL ret = FALSE;
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
SC_HANDLE hsev = NULL;
if(scHandle != NULL)
{
hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
DWORD err = GetLastError();
if (err == ERROR_SERVICE_DOES_NOT_EXIST)
{
ret = FALSE;
}
else
{
ret = TRUE;
}
if(hsev != NULL)
{
CloseServiceHandle(hsev);
CloseServiceHandle(scHandle);
}
}
return ret;
} void JXServiceControl::SetServiceName(const char * str)
{
strcpy_s(sSname,MAX_PATH,str);
} void JXServiceControl::SetServiceShowName(const char *str)
{
strcpy_s(sShowName,MAX_PATH,str);
} void JXServiceControl::SetExePath(const char *str)
{
strcpy_s(sSvcExePath,MAX_PATH,str);
}
JXServiceControl.cpp
转载请注明出处....
代码栗子:http://pan.baidu.com/s/1WHQ5w