Reputation: 203
I need to get the status of Windows "print spooler" service in my C++ application.
Upvotes: 5
Views: 12381
Reputation: 832
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;
}
Upvotes: 9
Reputation: 135
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;
}
Upvotes: 7
Reputation: 11880
Use QueryServiceStatus or QueryServiceStatusEx. There are plenty of examples on the web on how these are used.
Upvotes: 5