Check for a state of a service in Windows using C via Windows API / function [duplicate]

StackOverflow https://stackoverflow.com/questions/23622101

  •  21-07-2023
  •  | 
  •  

Pregunta

Hi recently I used the windows system call

popen ("sc query winmgmt | find STATE","r");

to get the state of the windows management instrumentation but I've been told to use a windows function / API instead

Is this possible? with C only?

¿Fue útil?

Solución

Assuming you know how to use the windows API, the function you're looking for is QueryServiceStatusEx.

A simple example of using QueryServiceStatusEx:

// Services (MSDN):
//   http://msdn.microsoft.com/en-us/library/ms685141(v=vs.85).aspx

#include <windows.h>
#include <stdio.h>

int main() {
  char *serviceName = "winmgmt";

  SC_HANDLE sch = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  if (sch == NULL){
    printf("OpenSCManager failed\n");
    return 1;
  }

  SC_HANDLE svc = OpenService(sch, serviceName, SC_MANAGER_ALL_ACCESS);
  if (svc == NULL){
    printf("OpenService failed\n");
    return 1;
  }

  SERVICE_STATUS_PROCESS stat;
  DWORD needed = 0;
  BOOL ret = QueryServiceStatusEx(svc, SC_STATUS_PROCESS_INFO,
                                  (BYTE*)&stat, sizeof stat, &needed);
  if (ret == 0){
    printf("QueryServiceStatusEx failed\n");
    return 1;
  }

  if (stat.dwCurrentState == SERVICE_RUNNING){
    printf("%s is running\n", serviceName);
  }else{
    printf("%s is NOT running\n", serviceName);
  }

  CloseServiceHandle(svc);
  CloseServiceHandle(sch);

  return 0;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top