본문 바로가기
#컴퓨터 과학 [Computer Science]/운영체제 (Operating System)

[OS - 🍎 macOS] macOS 현재 사용자 이름 구하기 (Getting the currently logged in user on macOS)

by cy_mos 2019. 11. 20.
반응형

👓 001. SCDynamicStoreCopyConsoleUser(_:_:_:)

// MARK: - Returns information about the user currently logged into the system.

func SCDynamicStoreCopyConsoleUser(_ store: SCDynamicStore?, 
                                 _ uid: UnsafeMutablePointer<uid_t>?, 
                                 _ gid: UnsafeMutablePointer<gid_t>?) -> CFString?

 

👓 002. SCDynamicStoreKeyCreateConsoleUser(_:)

// MARK: - Creates a key that can be used to receive notifications when the current console user changes.

func SCDynamicStoreKeyCreateConsoleUser(_ allocator: CFAllocator?) -> CFString

📔 Getting the current console user Source Code by Swift

Get-CurrentUserName.swift
0.00MB

/*
 * Copyright (c) 2019 양창엽. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
        macOS 환경에서의 로그인 된 실 사용자의 이름을 구하여 반환합니다.
        
        - Returns: String? (Optional)
*/
func getCurrentUserName() -> String? {
        // Creates a new session used to interact with the dynamic store maintained by the System Configuration server.
        let store = SCDynamicStoreCreate(nil, "GetConsoleUser" as CFString, nil, nil)

        // Returns information about the user currently logged into the system.
        guard let result = SCDynamicStoreCopyConsoleUser(store, nil, nil) else {
            // MARK: https://developer.apple.com/library/archive/qa/qa1133/_index.html
            return nil
        }

        return result as String?
}

📔 Getting the current console user Source Code by Objective-C

#include <assert.h>
#include <SystemConfiguration/SystemConfiguration.h>

static CFStringRef CopyCurrentConsoleUsername(SCDynamicStoreRef store);
    // defined above

static CFStringRef gCurrentConsoleUser;

static void MyNotificationProc(
    SCDynamicStoreRef	store,
    CFArrayRef          changedKeys,
    void *              info
)
    // Called out of our runloop when the current console user value 
    // changes in the dynamic store. It's possible to get multiple 
    // redundant notifications, so we debounce the notification by checking 
    // for changes relative to gCurrentConsoleUser.
{
    #pragma unused(changedKeys)
    #pragma unused(info)
    CFStringRef         currentConsoleUser;
    Boolean             didChange;

    // Get the current console user.

    currentConsoleUser = CopyCurrentConsoleUsername(store);

    // See if it changed.

    didChange = (gCurrentConsoleUser != NULL) != (currentConsoleUser != NULL);
    if ( ! didChange && (gCurrentConsoleUser != NULL) ) {
        assert(currentConsoleUser != NULL); // because if it was NULL, 
                                            // didChange would already be true
        didChange = ! CFEqual(gCurrentConsoleUser, currentConsoleUser);
    }

    // If it did, log that fact and remember the current value.

    if (didChange) {
        if (gCurrentConsoleUser != NULL) {
            CFRelease(gCurrentConsoleUser);
        }
        gCurrentConsoleUser = currentConsoleUser;
        if (gCurrentConsoleUser != NULL) {
            CFRetain(gCurrentConsoleUser);
        }

        CFShow(gCurrentConsoleUser);
    }
}

int main(int argc, char **argv)
{
    #pragma unused(argc)
    #pragma unused(argv)
    Boolean             success;
    SCDynamicStoreRef   store;
    CFStringRef         key;
    CFArrayRef          keys;
    CFRunLoopSourceRef  rls;

    // Set up our connection to the dynamic store so that notifications are 
    // delivered by calling MyNotificationProc.

    store = SCDynamicStoreCreate(
        NULL, 
        CFSTR("com.apple.dts.ConsoleUser"), 
        MyNotificationProc, 
        NULL
    );
    assert(store != 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);

    // Print the current value.

    gCurrentConsoleUser = CopyCurrentConsoleUsername(store);
    CFShow(gCurrentConsoleUser);

    // Run forever printing any changes.

    CFRunLoopRun();

    // Clean up code. This simple tool will never execute this code 
    // (because CFRunLoopRun will never return), but I've left it here 
    // in case you adapt the code for a more complex situation.

    if (gCurrentConsoleUser != NULL) {
        CFRelease(gCurrentConsoleUser);
    }
    CFRunLoopSourceInvalidate(rls);
    CFRelease(rls);
    CFRelease(keys);
    CFRelease(key);
    CFRelease(store);

    return EXIT_SUCCESS;
}

static CFStringRef CopyCurrentConsoleUsername(SCDynamicStoreRef store)
    // Returns the name of the current console user, or NULL if there is 
    // none. store may be NULL, in which case a transient dynamic store 
    // session is used.
{
    CFStringRef result;

    result = SCDynamicStoreCopyConsoleUser(store, NULL, NULL);

    // If the current console user is "loginwindow", treat that as equivalent 
    // to none.

    if ( (result != NULL) && CFEqual(result, CFSTR("loginwindow")) ) {
        CFRelease(result);
        result = NULL;
    }

    return result;
}

🚀 REFERENCE

 

Technical Q&A QA1133: Determining console user login status

Technical Q&A QA1133 Determining console user login status Important: This document is no longer being updated. For the latest information about Apple SDKs, visit the documentation website. Q:  How do I tell whether a console user is currently logged in? A

developer.apple.com

 

SCDynamicStoreCopyConsoleUser(_:_:_:) - SystemConfiguration | Apple Developer Documentation

Function SCDynamicStoreCopyConsoleUser(_:_:_:) Returns information about the user currently logged into the system. DeclarationParametersstoreThe dynamic store session that should be used for communication with the server. Pass NULL to use a temporary sess

developer.apple.com

 

SCDynamicStoreKeyCreateConsoleUser - SystemConfiguration | Apple Developer Documentation

Function SCDynamicStoreKeyCreateConsoleUser Creates a key that can be used to receive notifications when the current console user changes. DeclarationParametersallocatorThe allocator that should be used to allocate memory for this key. This parameter may b

developer.apple.com

 

Swift: How to get Console User, UID, and GID via SCDynamicStoreCopyConsoleUser?

I am able to get the Username, UID and GID from SCDynamicStoreCopyConsoleUser using python: #!/usr/bin/python from SystemConfiguration import SCDynamicStoreCopyConsoleUser cfuser =

stackoverflow.com

반응형

댓글