The Bird
The Bird

Reputation: 407

How to get the logged on user from a process running as root?

I have a program running as root and call another program to run(A).

I want A to run when the user logs on. I've used command: su - 'username' -c A,

or in the A main function, I've called: setuid(current_uid_logged).

But I don't know the way to get the user-name of the logged on user, or the uid in the root process.

Ways that I've tried: getenv("USERNAME") or getlogin() always return root account.

I've confused with getlogin(), my program is running when kernel start and wait for user login (I have a thread to wait a Finder process (Mac OSX) running to detect user logged on), wait 10 seconds and call getlogin() but sometime, it returned root but can return user login. I think Finder process is running when user logged on.

But when I call my app to run with sudo command, getlogin() always returns current user logged on.

How do I do this?

Upvotes: 0

Views: 1816

Answers (2)

sarnold
sarnold

Reputation: 104050

getlogin(3) returns the name of the user who owns the process's controlling terminal. This has nothing to do with the username of whoever might log in to the GUI of the operating system. Instead, getlogin(3) and getuid(2) will only ever return the name / uid of the user account that started the program -- they have more to do with the process history than with any user sitting in front of the computer.

There are similar stories with the environment variables USER and LOGNAME -- if either one was set in a process, it was by a process higher in the process's call tree. It too cannot be influenced by whichever user eventually sits in front of the computer.

I'm sure there is some mechanism to discover the currently-logged-on user on an OS X machine, but it won't be a traditional Unix API that provides it to you.

Upvotes: 1

Related Questions