Reputation: 1355
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
Reputation: 2792
On macOS, multiple users can be logged in at once. Use utmpx
functions to iterate over user sessions.
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.
/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
Reputation: 545
SCDynamicStoreCopyConsoleUser() might work for you. It will return uid and gid of the current console user.
https://developer.apple.com/library/mac/#qa/qa2001/qa1133.html
Upvotes: 5
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