How can I track the status changes of windows services in xp windows?

I am trying to write a C program that can detect when some Windows services (such as NT services) are started or stopped.

There seems to be a NotifyServiceStatusChange function, but this is only available on Vista and Windows 7. I'm trying to do this on Win XP, so what's the best way? Is there any other than continuous survey?

edit:

Can anyone give an answer in C? I'm fine with C ++ too, but I would like to stay away from scripts.

+4
source share
2 answers

It looks like the closest you can get in XP is QueryServiceStatusEx (one service) or EnumServicesStatusEx (several services).

To avoid calling any of them again, some recommend installing WMI by requesting the Win32_Service state property. See the bottom of this thread for more details.

The following is a (basic) WMI script for monitoring the status of a reuse service:

 strComputer = "." Set objSWbemServices = GetObject("winmgmts:" &_ "{impersonationLevel=impersonate}!" &_ "\\" & strComputer & "\root\cimv2") Set objEventSource = objSWbemServices.ExecNotificationQuery( _ "SELECT * FROM __InstanceModificationEvent " &_ "WITHIN 10 " &_ "WHERE TargetInstance " &_ "ISA 'Win32_Service' " &_ "AND TargetInstance.Name = 'alerter'") Set objEventObject = objEventSource.NextEvent() Wscript.Echo "The status of the alerter service just changed." 

The above and additional examples can be found on this TechNet page .

+3
source

You will need to do this by interrogating. Put the code in a separate thread and send it to sleep until it is reasonable. Say every second, maybe even 5 seconds, to minimize system performance.

As an example of 'c' for one service:

// various descriptors and strings plus ... SERVICE_STATUS ssStatus; ...

  schSCManager = OpenSCManager( ServiceComputerNameStr, NULL, SC_MANAGER_ALL_ACCESS ); if ( schSCManager == NULL ) { // ... error stuff goto cleanup; } scphService = OpenService( schSCManager, ServiceNameStr, // SERVICE_QUERY_STATUS ); SERVICE_ALL_ACCESS ); if ( scphService == NULL ) { // ... error stuff goto cleanup; } if ( !QueryServiceStatus(scphService, ssStatus) ) { // ... error stuff goto cleanup; } 

The result you want will be in ssStatus.dwCurrentState.

0
source

All Articles