How to get a user name of the interactive login session that a process is running in?

119 Views Asked by At

From my macOS GUI app (written in Swift and C) how do I find out the interactive user name for the login session where my process is running?

I know that I can use getuid() and geteiud() to get the user ID that the process is running under, but that doesn't work if the GUI app is elevated to root with the call to AuthorizationExecuteWithPrivileges. In that case I still get the root user, when I need the name of the interactive user whose desktop the app is running in.

2

There are 2 best solutions below

0
ahmd0 On BEST ANSWER

macOS has a special function for that: SCDynamicStoreCopyConsoleUser. Here's the example how you can use it.

1
lcheylus On

You could use getlogin/getlogin_r functions from unistd.h to get the name of the user logged in on the controlling terminal of the process.

See getlogin manpage.