Service Manager

//用于windows服务和NT式驱动程序的安装,卸载,运行,停止操作。
//SCM.cpp
///
 
#define OPER_INSTALL	0x1  //安装
#define OPER_START		0x2  //运行
#define OPER_STOP		0x3  //停止
#define OPER_UNINSTALL  0x4  //卸载
#define OPER_UNKNOWN	0x5

#define IDX_SERV_OPER 1  //argv[1]:operation-type
#define IDX_SERV_NAME 2  //argv[2]:service name
#define IDX_SERV_PATH 3  //argv[3]:service path

#include 
#include 
#include 

SC_HANDLE hSCM;
SC_HANDLE hServ;

//提示错误信息
VOID ReportErr(int errCode)
{
	LPVOID lpMsgBuf;
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
				  NULL,
				  errCode,
				  MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
				  (LPTSTR)&lpMsgBuf,
				  0,
				  NULL);

	if(lpMsgBuf != NULL)
		printf("Err Info:\n%S\n", lpMsgBuf);
	else
		printf("can't format err message\n");
}

//创建服务
BOOL Create(LPTSTR lpszServiceName, LPTSTR lpszServicePath)
{
	hServ = CreateService(hSCM,
		lpszServiceName, 
		lpszServiceName,
		SERVICE_ALL_ACCESS,
		SERVICE_KERNEL_DRIVER,
		SERVICE_DEMAND_START,
		SERVICE_ERROR_IGNORE,
		lpszServicePath,
		NULL,NULL,NULL,NULL,NULL);
	if(hServ == NULL)
		return FALSE;
	return TRUE;
}

//停止所有依赖服务。
BOOL StopDependentServices(SC_HANDLE schServ)
{
	DWORD i, dwBytesNeeded, dwCount;
	LPENUM_SERVICE_STATUS lpDependencies = NULL;
	ENUM_SERVICE_STATUS ess;
	SERVICE_STATUS_PROCESS ssp;
	SC_HANDLE hDepServ;

	if(EnumDependentServices(schServ,
		SERVICE_ACTIVE,
		lpDependencies,
		0,
		&dwBytesNeeded,
		&dwCount))
	{return TRUE;} //没有依赖的服务
	else
	{
		if(GetLastError() != ERROR_MORE_DATA)
			return FALSE;
		lpDependencies = (LPENUM_SERVICE_STATUS)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,dwBytesNeeded);
		if(lpDependencies == NULL)
			return FALSE;
		__try
		{
			if(!EnumDependentServices(schServ,
									  SERVICE_ACTIVE,
									  lpDependencies,
								      0,
									  &dwBytesNeeded,
									  &dwCount))
			return FALSE;
			for(i=0; i


 

 

你可能感兴趣的:(Windows,控制台程序,service,manager,null,access,path,file)