码迷,mamicode.com
首页 > Windows程序 > 详细

windows服务监控和操作相关

时间:2015-08-07 11:05:57      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:服务

代码中实现了删除服务,启动服务,停止服务,检测服务是否运行和服务是否存在等功能:


#pragma  once

#include <Windows.h>
#include <tchar.h>


//删除服务
/*
返回:1:表示成功
0:打开失败
-1:表示打开SCManager失败
*/
int deleteService(LPCWSTR sSname)
{
	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 0;
		}
		CloseServiceHandle(scHandle);
	}
	else	return -1;
	return 1;
}
//启动KH客户端服务
void startService(LPCWSTR sSname)
{
	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,0,NULL);
			DWORD err = 0;
			if (isSucess  == 0)
			{
				err = GetLastError();
			}
			CloseServiceHandle(hscv);
		}
		CloseServiceHandle(scHandle);
	}
}
//停止KH客户端服务
void stopService(LPCWSTR sSname)
{
	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 isSvsRuning(LPCWSTR sSname)
{
	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 isSvsExist(LPCWSTR sSname)
{
	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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

windows服务监控和操作相关

标签:服务

原文地址:http://blog.csdn.net/qingzai_/article/details/47335753

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!