|
| 1 | +package main |
| 2 | + |
| 3 | +/* |
| 4 | +#cgo CFLAGS: -I. |
| 5 | +#include "watch.h" |
| 6 | +*/ |
| 7 | +import "C" |
| 8 | + |
| 9 | +import ( |
| 10 | + "fmt" |
| 11 | + "sync" |
| 12 | + "syscall" |
| 13 | + "os" |
| 14 | + "os/signal" |
| 15 | + "context" |
| 16 | + "runtime" |
| 17 | + "time" |
| 18 | +) |
| 19 | + |
| 20 | +const keyPath = `SOFTWARE\SAAZOD\ManagedPosix` |
| 21 | + |
| 22 | +type listener func(regPath string, event uint32) bool |
| 23 | + |
| 24 | +var listeners = map[string]listener{} |
| 25 | + |
| 26 | +func main() { |
| 27 | + runtime.GOMAXPROCS(runtime.NumCPU()) |
| 28 | + ctx, _ := cancelHandler() |
| 29 | + wg := &sync.WaitGroup{} |
| 30 | + wg.Add(1) |
| 31 | + go func(wg *sync.WaitGroup) { |
| 32 | + time.Sleep(time.Millisecond) |
| 33 | + fmt.Printf("INFO:\tLooking for changes in '%s'...\n", keyPath) |
| 34 | + defer wg.Done(); |
| 35 | + select { |
| 36 | + case <-ctx.Done(): |
| 37 | + fmt.Printf("INFO:\tGot shutdown signal...\n") |
| 38 | + default: |
| 39 | + } |
| 40 | + err := RegListen(C.HKEY_LOCAL_MACHINE, keyPath, func(kp string, event uint32) bool { |
| 41 | + fmt.Printf("INFO:\t'%s' changed (%d)\n", kp, event) |
| 42 | + select { |
| 43 | + case <-ctx.Done(): |
| 44 | + fmt.Printf("DEBUG:\t context is dead\n") |
| 45 | + return false |
| 46 | + default: |
| 47 | + return true |
| 48 | + } |
| 49 | + }) |
| 50 | + if err != nil { |
| 51 | + fmt.Printf("ERR:\t%s", err) |
| 52 | + } |
| 53 | + }(wg) |
| 54 | + |
| 55 | + fmt.Println("Waiting...") |
| 56 | + wg.Wait() |
| 57 | + fmt.Println("Goodbye") |
| 58 | +} |
| 59 | + |
| 60 | +func RegListen(hKey C.HKEY, regPath string, cb listener) error { |
| 61 | + cstr := C.CString(regPath) |
| 62 | + listeners[regPath] = cb |
| 63 | + result := C.reg_listen(hKey, cstr) |
| 64 | + if result == C.ERROR_SUCCESS { |
| 65 | + return nil |
| 66 | + } |
| 67 | + |
| 68 | + return syscall.Errno(result) |
| 69 | +} |
| 70 | + |
| 71 | +//export reg_global_listener |
| 72 | +func reg_global_listener(cstr *C.char, dwEvent uint32) bool { |
| 73 | + keyPath := C.GoString(cstr) |
| 74 | + handler, ok := listeners[keyPath] |
| 75 | + if !ok { |
| 76 | + fmt.Printf("ERROR:\tno listener for '%s'\n", keyPath) |
| 77 | + return false; |
| 78 | + } |
| 79 | + |
| 80 | + result := handler(keyPath, dwEvent) |
| 81 | + return result |
| 82 | +} |
| 83 | + |
| 84 | + |
| 85 | +// cancelHandler returns cancellation context and function for graceful shutdown |
| 86 | +func cancelHandler() (context.Context, context.CancelFunc) { |
| 87 | + ctx, cancelFn := context.WithCancel(context.Background()) |
| 88 | + |
| 89 | + signals := make(chan os.Signal, 1) |
| 90 | + signal.Notify(signals, os.Interrupt) |
| 91 | + |
| 92 | + go func() { |
| 93 | + <-signals |
| 94 | + cancelFn() |
| 95 | + signal.Stop(signals) |
| 96 | + }() |
| 97 | + |
| 98 | + return ctx, cancelFn |
| 99 | +} |
0 commit comments