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

11

3

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?

gak

Posted 2010-08-26T02:44:30.983

Reputation: 7 037

1Wait GUI and command line? Both? Or just command line? I'm confused. – Vervious – 2010-08-26T02:46:55.823

@Nano8Blazex, made the question more clear for you. – gak – 2010-08-26T03:10:43.977

:D that's great! – Vervious – 2010-08-26T04:29:34.240

Answers

19

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;
}

Chris Johnsen

Posted 2010-08-26T02:44:30.983

Reputation: 31 786

See manpage getlogin. – Itachi – 2014-12-24T11:32:58.337

stat -f '%u %Su' /dev/console works perfectly. Thank you – Akshat – 2019-11-21T21:13:57.680

7

Via the command line, who and users should work.

John T

Posted 2010-08-26T02:44:30.983

Reputation: 149 037

Ah, who and look for "console". Thanks. – gak – 2010-08-26T03:09:36.940

1@Gerald: Using who is not accurate on my 10.4 system when using fast user switching (the system I am using right now shows another user on “console” even though my GUI session is the active one). Maybe it is more reliable in newer versions. – Chris Johnsen – 2010-08-26T05:39:09.253

@JohnT: if you have 2 users logged in (user switching), the who command will list both the users associated with 'console'. This does not work correctly. – Akshat – 2019-11-21T21:12:02.610