How can you find out the currently logged in user in the OS X GUI?

Trying to find out if a particular user is logged into the machine, specifically the user using the graphical user interface.

Is this possible via command line?


GUI:

  • Open the Accounts preference pane in System Preferences. The pre-selected user account will be the active user account.
  • If fast user switching is active its menu extra (the menu on the right side of the menu bar) can be configured to show the name of the active user.

Command Line:

  • Check the owner of /dev/console

    stat -f '%u %Su' /dev/console
    
  • Write a program that uses the official API (SCDynamicStoreCopyConsoleUser; see below)

In a C program:

The C code in Technical Q&A QA1133: Determining console user login status shows how to determine which user owns the active GUI session.

For example:

/* Adapted from QA1133:
 *    http://developer.apple.com/mac/library/qa/qa2001/qa1133.html
 */
#include <assert.h>
#include <SystemConfiguration/SystemConfiguration.h>

int main(int argc, char **argv) {
    SCDynamicStoreRef store;
    CFStringRef name;
    uid_t uid;
#define BUFLEN 256
    char buf[BUFLEN];
    Boolean ok;

    store = SCDynamicStoreCreate(NULL, CFSTR("GetConsoleUser"), NULL, NULL);
    assert(store != NULL);
    name = SCDynamicStoreCopyConsoleUser(store, &uid, NULL);
    CFRelease(store);

    if (name != NULL) {
        ok = CFStringGetCString(name, buf, BUFLEN, kCFStringEncodingUTF8);
        assert(ok == true);
        CFRelease(name);
    } else {
        strcpy(buf, "<none>");
    }

    printf("%d %s\n", uid, buf);

    return 0;
}

Via the command line, who and users should work.