Daemon to know when a user logs into the MAC

≯℡__Kan透↙ 提交于 2019-12-05 14:28:53

Use SCDynamicStoreCopyConsoleUser to get the console user name.

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

Store consoleUserName in some member variable. Now creates a session to interact with the dynamic store maintained by the System Configuration server using 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);   

Implement callBackFunction function. You will get callback when the console user value changes.

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!