EnumServicesStatus – Enumerate NT services

Every machine installed with Windows NT Operating system and above will have NT services running with it. Developers will also write some Win32 NT Services for applications. This article describes how to enumerate the NT Services installed in the system using the Win32 API EnumServicesStatus.

Each NT machine has a Service Control Manager (SCM), which manages the NT Services database. The user who is trying to programmatically access the SCM, should have Administrative rights.

Before using the API EnumServicesStatus the Service Control Manager (SCM) Database must be opened first. This is done using the function OpenSCManager. The handle (SC_HANDLE type) returned will be used for subsequent operations to enumerate the NT services. Then the SCM handle should be closed using CloseServiceHandle.

See the following sample code. This uses both OpenSCManager and EnumServicesStatus to achieve the purpose.

//EnumServ.cpp - Sample code using OpenSCManager and EnumServicesStatus to enumerate NT Services installed in a machine
#include <stdio.h>
#include <Windows.h>
void main()
{

//Open the Service Control Manager
SC_HANDLE sc = ::OpenSCManager (NULL,NULL,SC_MANAGER_ENUMERATE_SERVICE);
//Check if OpenSCManager returns NULL. Otherwise proceed
if (sc != NULL)
{
printf("Opened SCM using OpenSCManager n");
ENUM_SERVICE_STATUS service_data, *lpservice;
BOOL retVal;
DWORD bytesNeeded,srvCount,resumeHandle = 0,srvType, srvState;
srvType = SERVICE_WIN32;
srvState = SERVICE_STATE_ALL;
//Call EnumServicesStatus using the handle returned by OpenSCManager
retVal = ::EnumServicesStatus (sc,srvType,srvState,&service_data,sizeof(service_data),
&bytesNeeded,&srvCount,&resumeHandle);
DWORD err = GetLastError();
//Check if EnumServicesStatus needs more memory space
if ((retVal == FALSE) || err == ERROR_MORE_DATA)
{
DWORD dwBytes = bytesNeeded + sizeof(ENUM_SERVICE_STATUS);
lpservice = new ENUM_SERVICE_STATUS [dwBytes];
EnumServicesStatus (sc,srvType,srvState,lpservice,dwBytes,
&bytesNeeded,&srvCount,&resumeHandle);
}
printf("Count of NT Services using EnumServicesStatus : %dnn",srvCount);
for(int i=0;i<srvCount;i++)
{
printf("%sn",lpservice[i].lpDisplayName);
}
}

//Close the SC_HANLDE returned by OpenSCManager
CloseServiceHandle(sc);
}

The above sample is written as a console application. This can be directly copied and compiled in a console application. This will print all the available WIN32 NT services in the system. The include file windows.h includes the necessary definitions for EnumServicesStatus and OpenSCManager.