遍历服务


#include <windows.h>

int main(int argc, char* argv[])
{
	//获得服务管理器SCM的句柄
	SC_HANDLE sc=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
	if (sc == NULL)
	{
		return 0;
	}
	LPENUM_SERVICE_STATUS lst=NULL;
	DWORD dwCount=0;
	DWORD dwSize=0;
	//第一次调用来得到需要多大的内存区
	BOOL bRet = EnumServicesStatus(sc,SERVICE_WIN32|SERVICE_DRIVER,SERVICE_STATE_ALL,
		lst,dwSize,&dwSize,&dwCount,NULL);
	if (!bRet && dwSize==0)
	{
		CloseServiceHandle(sc);
		return 0;
	}
	//申请需要的内存
	lst=(LPENUM_SERVICE_STATUS)LocalAlloc(LPTR,dwSize);
	if (lst == NULL)
	{
		CloseServiceHandle(sc);
		return 0;
	}
	//第二次调用来得所有服务的信息
	LPQUERY_SERVICE_CONFIG lpServiceInfo = NULL;
	bRet = EnumServicesStatus(sc,SERVICE_WIN32,SERVICE_STATE_ALL,
		lst,dwSize,&dwSize,&dwCount,NULL);
	if (!bRet && dwSize==0)
	{
		CloseServiceHandle(sc);
		LocalFree(lst);
		return 0;
	}
	printf("%-28s%-8s%-12s%s\n\n", "服务名", "状态", "启动类型", "关联程序");
	SC_HANDLE hService = NULL;
	//开始打印枚举出的服务信息
	for(DWORD i=0;idwStartType)
		{
		case SERVICE_BOOT_START:case SERVICE_SYSTEM_START:case SERVICE_AUTO_START:
			{	
				printf("%-12s", "自启动");
			}
			break;
		case SERVICE_DEMAND_START:
			{
				printf("%-12s", "手动启动");
			}
			break;
		case SERVICE_DISABLED:
			{
				printf("%-12s", "已禁用");
			}
			break;
		}
		if (lpServiceInfo->lpBinaryPathName != NULL)
		{
			printf("%s\n", lpServiceInfo->lpBinaryPathName);
		}
		CloseServiceHandle(hService); 
		LocalFree(lpServiceInfo);
	}
	printf("共计 %d 个服务\n", dwCount);
	CloseServiceHandle(sc);
	LocalFree(lst);
	return 0;
}


评论列表