5

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

user519986
  • 193
  • 1
  • 4
  • 11
  • I don't know much about C++, but if you are using C++.NET, then I'd think you could use System.ServiceProcess.ServiceController. If not using .NET, then I don't know. – Matt Oct 18 '11 at 13:39
  • Related: http://stackoverflow.com/questions/5442241/windows-service-status-c – jro Oct 18 '11 at 13:40

3 Answers3

9

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;
}
Thibaut Mattio
  • 822
  • 9
  • 17
7

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;

}

shikarssj
  • 135
  • 2
  • 5
5

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

seva titov
  • 11,720
  • 2
  • 35
  • 54