Get user name from user id

In a background daemon(run as root), I want to get user name from a user id(like 501).

I tried to use getpwuid() function, but the pw_name it returns is root.

Is there any other API I can use to get user name from any valid user id?


One more related question:

How can I get the currently active logged-in user in a background daemon considering fast user switching?

There seems to be a command called logname, but I have no idea how to do it programmatically.

Thanks!

Replies

Is there any other API I can use to get user name from any valid user id?

You can use

getpwuid
for that. If you always get
root
back, that’s probably because you’re always passing it 0 as the UID. If you pass it a different UID, you’ll get a different name.
let p = getpwuid(501)!
print(String(cString: p.pointee.pw_name))
// prints "quinn" on my machine

How can I get the currently active logged-in user in a background daemon considering fast user switching?

I’m going to caution against doing this. In my experience, most folks who ask this question are suffering from architectural problems. For example, in your case, you’re asking about the “currently active logged-in user”, but macOS can have multiple currently active GUI login sessions, including at most one on the console and zero or more logged in via screen sharing.

I discuss this issue in detail in QA1133 Determining console user login status and the documents it links to.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

ok