1 | #pragma once |
---|
2 | |
---|
3 | #include <CoreFoundation/CoreFoundation.h> |
---|
4 | #include <unistd.h> |
---|
5 | #include <sys/event.h> |
---|
6 | |
---|
7 | |
---|
8 | using callbackType = void (CFFileDescriptorRef, CFOptionFlags, void *); |
---|
9 | using HandleFunction = std::function<void(int)>; |
---|
10 | |
---|
11 | static inline void noteProcDeath(CFFileDescriptorRef fdref, CFOptionFlags callBackTypes, void *info) { |
---|
12 | struct kevent kev; |
---|
13 | int fd = CFFileDescriptorGetNativeDescriptor(fdref); |
---|
14 | kevent(fd, NULL, 0, &kev, 1, NULL); |
---|
15 | // take action on death of process here |
---|
16 | NSLog(@"process with pid '%u' died\n", (unsigned int)kev.ident); |
---|
17 | //sendUserNotification(APP_IDSTR, @"The I2P router has stopped."); |
---|
18 | CFFileDescriptorInvalidate(fdref); |
---|
19 | CFRelease(fdref); // the CFFileDescriptorRef is no longer of any use in this example |
---|
20 | } |
---|
21 | // one argument, an integer pid to watch, required |
---|
22 | int watchPid(int pid, callbackType callback = noteProcDeath) { |
---|
23 | int fd = kqueue(); |
---|
24 | struct kevent kev; |
---|
25 | EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL); |
---|
26 | kevent(fd, &kev, 1, NULL, 0, NULL); |
---|
27 | CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, fd, true, callback, NULL); |
---|
28 | CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack); |
---|
29 | CFRunLoopSourceRef source = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, fdref, 0); |
---|
30 | CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode); |
---|
31 | CFRelease(source); |
---|
32 | /* |
---|
33 | seconds |
---|
34 | The length of time to run the run loop. If 0, only one pass is made through the run loop before returning; |
---|
35 | if multiple sources or timers are ready to fire immediately, only one (possibly two if one is a version |
---|
36 | 0 source) will be fired, regardless of the value of returnAfterSourceHandled. |
---|
37 | */ |
---|
38 | CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, false); |
---|
39 | return 0; |
---|
40 | } |
---|