How to get the status of a service programmatically (Running/Stopped)

10,330

Solution 1

Use QueryServiceStatus or QueryServiceStatusEx. There are plenty of examples on the web on how these are used.

Solution 2

The function that @shikarssj provided is working perfectly, it only requires admin rights when loading the service.

Here is a version that does not ask for full permission:

#include <Windows.h>

int GetServiceStatus( const char* name )
{
    SC_HANDLE theService, scm;
    SERVICE_STATUS m_SERVICE_STATUS;
    SERVICE_STATUS_PROCESS ssStatus;
    DWORD dwBytesNeeded;


    scm = OpenSCManager( nullptr, nullptr, SC_MANAGER_ENUMERATE_SERVICE );
    if( !scm ) {
        return 0;
    }

    theService = OpenService( scm, name, SERVICE_QUERY_STATUS );
    if( !theService ) {
        CloseServiceHandle( scm );
        return 0;
    }

    auto result = QueryServiceStatusEx( theService, SC_STATUS_PROCESS_INFO,
        reinterpret_cast<LPBYTE>( &ssStatus ), sizeof( SERVICE_STATUS_PROCESS ),
        &dwBytesNeeded );

    CloseServiceHandle( theService );
    CloseServiceHandle( scm );

    if( result == 0 ) {
        return 0;
    }

    return ssStatus.dwCurrentState;
}

Solution 3

I couldn't find any good example using WinApi and C++. I tried and compiled the following and it works in Borland. Hope this helps someone.

int getServiceStatus(char* name) 
{
   SC_HANDLE theService,scm;
   SERVICE_STATUS m_SERVICE_STATUS;
   SERVICE_STATUS_PROCESS ssStatus;
   DWORD dwBytesNeeded;

   scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
   if (!scm) {
     ShowErr();
     return 0;
   }


   theService = OpenService(scm, name, SERVICE_ALL_ACCESS);
   if (!theService) {
     CloseServiceHandle(scm);
     ShowErr();
     return 0;
   }

   int result = QueryServiceStatusEx(theService, SC_STATUS_PROCESS_INFO, (LPBYTE)       
                                   &ssStatus, sizeof(SERVICE_STATUS_PROCESS), 
                                   &dwBytesNeeded);

CloseServiceHandle(theService);
CloseServiceHandle(scm);

if (result == 0) return 0; // fail query status

return ssStatus.dwCurrentState;

}

Share:
10,330
user519986
Author by

user519986

Updated on June 20, 2022

Comments

  • user519986
    user519986 almost 2 years

    I need to get the status of Windows "print spooler" service in my C++ application.