ytw
ytw

Reputation: 1355

How to get MacOsX Logged-in User's user id in Objective-C?

Please let me know how to get the currently logged-in user's user id in Objective-C. I would like to get the user id of the logged-in user that's currently using the computer locally. My command-line program is running as root and I want to find the currently logged-in user's user id. Thanks.

Upvotes: 2

Views: 4136

Answers (3)

Graham Miln
Graham Miln

Reputation: 2792

On macOS, multiple users can be logged in at once. Use utmpx functions to iterate over user sessions.

SCDynamicStoreCopyConsoleUser

To discover the user with the active graphical session, use the SCDynamicStoreCopyConsoleUser function in the SystemConfiguration.framework.

Note that Apple's QA1133 mentions this function may be deprecated in the future:

Warning: The System Configuration framework mechanism for determining the current console user has a number of important caveats:

  • It assumes that the computer has a single GUI console. While that's true currently, it may not be true forever. If you use this technique you will have to change your code if this situation changes.
  • It has no way of indicating that multiple users are logged in.
  • It has no way of indicating that a user is logged in but has switched to the login window.

Because of these issues, routines like SCDynamicStoreCopyConsoleUser exist only for compatibility purposes. It's likely that they will be formally deprecated in a future version of Mac OS X.

Owner of /dev/console

An alternative approach is to fstat the path /dev/console:

struct stat info;
if (lstat(_PATH_CONSOLE,&info) == 0) {
    printf("%s is owned by %d\n",_PATH_CONSOLE,info.st_uid);
}

Upvotes: 3

SG1
SG1

Reputation: 545

SCDynamicStoreCopyConsoleUser() might work for you. It will return uid and gid of the current console user.

https://developer.apple.com/library/mac/#documentation/Networking/Reference/SCDynamicStoreCopySpecific/Reference/reference.html

https://developer.apple.com/library/mac/#qa/qa2001/qa1133.html

Upvotes: 5

MJN
MJN

Reputation: 10818

You can use NSUserName(). This will return the name of the current logged in user.

NSString *userName = NSUserName();

Additionally, there is also an NSFullUserName() function.

NSFullUserName() // "John Doe"
NSUserName()     // "jdoe"

Upvotes: 4

Related Questions