Created
December 12, 2023 18:54
-
-
Save Sohamkadam333/16cea5e595f4bddbf8b58030e10e3bb3 to your computer and use it in GitHub Desktop.
Enumerates services in the specified service control manager database. The name and status of each service are provided.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To get the service name of a running service in Windows, you can use the EnumServicesStatus function to enumerate through the services in the Service Control Manager (SCM) database and retrieve information about each service, including its name. | |
#include <iostream> | |
#include <windows.h> | |
using namespace std; | |
int main() | |
{ | |
SC_HANDLE scmHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT|SC_MANAGER_ENUMERATE_SERVICE); | |
if(scmHandle == NULL) | |
{ | |
cerr<<"Error opening Service Control Manager, Error No: "<<GetLastError()<<endl; | |
} | |
DWORD bufferSize = 0; | |
DWORD servicesReturned = 0; | |
DWORD resumeHandle = 0; | |
EnumServicesStatus(scmHandle,SERVICE_WIN32,SERVICE_STATE_ALL,NULL,0,&bufferSize,&servicesReturned,&resumeHandle); | |
// buffer size error | |
if(GetLastError() != ERROR_MORE_DATA) | |
{ | |
cerr<<"Error getting buffer size"<<endl; | |
CloseServiceHandle(scmHandle); | |
system("PAUSE"); | |
return 1; | |
} | |
// Allocate buffer to get service Information | |
LPENUM_SERVICE_STATUS services = static_cast<LPENUM_SERVICE_STATUS>(malloc(bufferSize)); | |
if(services == NULL) | |
{ | |
cerr<<"Error allocating buffer "<<endl; | |
CloseServiceHandle(scmHandle); | |
system("PAUSE"); | |
return 1; | |
} | |
// Enumerate Services | |
if(EnumServicesStatus(scmHandle,SERVICE_WIN32,SERVICE_STATE_ALL,services,bufferSize,&bufferSize,&servicesReturned,&resumeHandle)) | |
{ | |
wcout<<"Service Names: "<<endl; | |
for(DWORD i = 0;i<servicesReturned;i++) | |
{ | |
wcout<<services[i].lpServiceName<<endl; | |
} | |
} | |
else | |
{ | |
cerr<<"Error Enumerating Services, Error No: "<<GetLastError()<<endl; | |
system("PAUSE"); | |
} | |
free(services); | |
CloseServiceHandle(scmHandle); | |
system("PAUSE"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment