1 year ago
#181454
M. Javad Mohebbi
WMI ExecNotificationQuery using golang
I am using this go WMI package to monitor windows processes which are starting and stopping. I have see the example an implemented my own methods using Win32_Process
and __InstanceCreationEvent
and __InstanceDeletionEvent
.
Here is the sample for __InstanceDeletionEvent
:
func (e *Events) deleteProcessNotify() error {
query := `
SELECT * FROM __InstanceDeletionEvent
WITHIN 1
WHERE TargetInstance ISA 'Win32_Process'
`
events := make(chan event)
q, err := wmi.NewNotificationQuery(events, query)
if err != nil {
return errors.New(
fmt.Sprintf("Failed to create NotificationQuery; %s", err),
)
}
go func() {
e.errCh <- q.StartNotifications()
}()
log.Println("Listening for events", CLS)
for {
select {
case ev := <-events:
fmt.Printf("[%v] Name: %v, Pid: %v, PPid: %v\n",
CLS,
ev.Instance.Caption, ev.Instance.ProcessId, ev.Instance.ParentProcessId,
)
case sig := <-e.sigs:
log.Printf("Got system signal %s; stopping", sig)
q.Stop()
return nil
case err := <-e.errCh: // Query will never stop here w/o error.
log.Printf("[ERR] Got StartNotifications error; %s", err)
return nil
}
}
}
Above code works find but Win32_Process
does not support ExitStatus and I decided to use Win32_ProcessTrace
. But when I am closing applications, nothing is happening under case ev := <-events:
this case.
Here is the method for Win32_ProcessTrace
:
func (e *Events) deleteProcessNotify__Trace() error {
query := `
SELECT * FROM __InstanceDeletionEvent
WITHIN 1
WHERE TargetInstance ISA 'Win32_ProcessTrace'
`
events := make(chan event)
q, err := wmi.NewNotificationQuery(events, query)
if err != nil {
return errors.New(
fmt.Sprintf("Failed to create NotificationQuery; %s", err),
)
}
go func() {
e.errCh <- q.StartNotifications()
}()
log.Println("Listening for events", CLS)
for {
select {
case ev := <-events:
// THIS EVENT IS NEVER OCCURRED AND
// I REALLY DONT KNOW WHY!!!
//
fmt.Println(ev)
//
//
//
case sig := <-e.sigs:
log.Printf("Got system signal %s; stopping", sig)
q.Stop()
return nil
case err := <-e.errCh: // Query will never stop here w/o error.
log.Printf("[ERR] Got StartNotifications error; %s", err)
return nil
}
}
}
go
wmi
wql
0 Answers
Your Answer