Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 327
user519986 Avatar asked Oct 18 '11 13:10

user519986


1 Answers

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;
}
like image 146
Thibaut Mattio Avatar answered Oct 26 '22 22:10

Thibaut Mattio