Daemon know when a user logs in to a MAC

I have a daemon (written in Obj C), and I would like to perform some actions when some user logs in. Is it possible for Daemon to know when a particular user logs in or logs out to OSX? Are there any notifications that occurred while logging in? I would like to avoid using Log in Item or Launch Agent. And also I would like to avoid timer polling in order to check the registered user.

+4
source share
1 answer

Use SCDynamicStoreCopyConsoleUserto get the console username.

CFStringRef  consoleUserName = nil;
uid_t        uid;
gid_t        gid;
consoleUserName = SCDynamicStoreCopyConsoleUser(NULL, &uid, &gid);

consoleUserName -. , , SCDynamicStoreCreate

     SCDynamicStoreRef   store;
     CFStringRef         key;
     CFArrayRef          keys;
     CFRunLoopSourceRef  rls;
     store = SCDynamicStoreCreate(
                                     NULL, 
                                     CFSTR("com.apple.dts.ConsoleUser"), 
                                     callBackFunction, 
                                     NULL
                                     );

    // Set it up to notify us when the console user value changes.

    key = SCDynamicStoreKeyCreateConsoleUser(NULL);
    assert(key != NULL);

    keys = CFArrayCreate(NULL, (const void **) &key, 1, &kCFTypeArrayCallBacks);
    //assert(keys != NULL);

    success = SCDynamicStoreSetNotificationKeys(store, keys, NULL);
    //assert(success);

    // Add it to the runloop.

    rls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
   // assert(rls != NULL);

    CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);


    mConsoleUserName = CopyCurrentConsoleUsername(store);
    CFRunLoopRun();

    CFRunLoopSourceInvalidate(rls);
    CFRelease(rls);
    CFRelease(keys);
    CFRelease(key);
    CFRelease(store);   

callBackFunction. , .

static void callBackFunction(
                               SCDynamicStoreRef    store,
                               CFArrayRef          changedKeys,
                               void *              info
                               )
{
    CFStringRef         currentConsoleUser;
    Boolean             didChange;

    // Get the current console user.

    currentConsoleUser = CopyCurrentConsoleUsername(store);

    if (currentConsoleUser == NULL)
    {
        return;
    }
    didChange = ! CFEqual(storedvalue, currentConsoleUser);
    if (![currentConsoleUser isEqualToString:@"loginwindow"])
    {
      // pass this value to some method
    }
}
+6

Source: https://habr.com/ru/post/1537863/


All Articles