source: launchers/macosx/obj-cpp/PidWatcher.h @ a92993e0

Last change on this file since a92993e0 was a92993e0, checked in by meeh <meeh@…>, 2 years ago

Added some more header files, and fixed much of the build system.

  • Property mode set to 100644
File size: 2.4 KB
Line 
1#pragma once
2
3#include <CoreFoundation/CoreFoundation.h>
4#include <unistd.h>
5#include <sys/event.h>
6#include <functional>
7
8#include "neither/either.hpp"
9#include "AppDelegate.h"
10
11using callbackType = void (CFFileDescriptorRef, CFOptionFlags, void *);
12using HandleFunction = std::function<void(int)>;
13/*
14class CallbackWrapper
15{
16    CallbackWrapper(HandleFunction func) : mCallback(func);
17    void operator(CFFileDescriptorRef fdref, CFOptionFlags callBackTypes, void *info) {
18        struct kevent kev;
19        int fd = CFFileDescriptorGetNativeDescriptor(fdref);
20        kevent(fd, NULL, 0, &kev, 1, NULL);
21        // take action on death of process here
22        NSLog(@"process with pid '%u' died\n", (unsigned int)kev.ident);
23
24        mCallback(0);
25        CFFileDescriptorInvalidate(fdref);
26        CFRelease(fdref);
27    }
28
29private:
30    HandleFunction mCallback;
31};
32*/
33
34static void noteProcDeath(CFFileDescriptorRef fdref, CFOptionFlags callBackTypes, void *info) {
35    struct kevent kev;
36    int fd = CFFileDescriptorGetNativeDescriptor(fdref);
37    kevent(fd, NULL, 0, &kev, 1, NULL);
38    // take action on death of process here
39    NSLog(@"process with pid '%u' died\n", (unsigned int)kev.ident);
40    sendUserNotification(APP_IDSTR, @"The I2P router has stopped.");
41    CFFileDescriptorInvalidate(fdref);
42    CFRelease(fdref); // the CFFileDescriptorRef is no longer of any use in this example
43}
44// one argument, an integer pid to watch, required
45int watchPid(int pid, callbackType callback = noteProcDeath) {
46    int fd = kqueue();
47    struct kevent kev;
48    EV_SET(&kev, pid, EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL);
49    kevent(fd, &kev, 1, NULL, 0, NULL);
50    CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, fd, true, callback, NULL);
51    CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack);
52    CFRunLoopSourceRef source = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, fdref, 0);
53    CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);
54    CFRelease(source);
55    /*
56    seconds
57    The length of time to run the run loop. If 0, only one pass is made through the run loop before returning;
58    if multiple sources or timers are ready to fire immediately, only one (possibly two if one is a version
59    0 source) will be fired, regardless of the value of returnAfterSourceHandled.
60    */
61    CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, false);
62    return 0;
63}
Note: See TracBrowser for help on using the repository browser.