Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

c - How can I monitor status changes of windows services under windows xp?

I'm trying to write a program in C, that can detect when some Windows services (aka. NT services) are started or stopped.

There seems to be a function NotifyServiceStatusChange, but that's 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 polling?

edit:

Is anybody able to give answer in C? I'm also ok with C++, but I'd like to stay away from scripting.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like the closest you can get in XP is QueryServiceStatusEx (single service) or EnumServicesStatusEx (multiple services).

To avoid repeatedly calling either of these, some recommend a WMI setup, querying Win32_Service's state property. See the bottom of this thread for more details.

The following is a (basic) WMI script to monitor the alerter service's status:

strComputer = "."
Set objSWbemServices = GetObject("winmgmts:" &_
    "{impersonationLevel=impersonate}!" &_
    "" & strComputer & "
ootcimv2")

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, may be found on this TechNet page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...