1

is there a way to get logged in user name from linux daemon? I tried

seteuid(1000);
std::string userName = getlogin();

But seems that this call fails and my application is terminated after. The general situation is following: some script that runs my daemon process. Inside of this daemon I start another UI process (lets call it A). Then in process A I'm trying to get logged in user name with way, described earlier. And my process A is terminated after getlogin call. Is there any reliable way to get logged in user name from process A?

rudolfninja
  • 467
  • 7
  • 24
  • 1
    Unexpected termination sounds like a crash, and to solve those you need to use a debugger to find out when and where in your program it happens. – Some programmer dude Apr 15 '20 at 10:42
  • I tried replace `getlogin()` with `"me"` (current user name) and everything was ok then. Thus I assumed that the problem somewhere in `getlogin`. In the comment to [this](https://stackoverflow.com/a/8953466/3113356) answer I found that `This function will also fail if you are not attached to a controlling terminal (e.g., when a process is daemonized)`, so looks like my case. That's why I'm asking about alternative ways. – rudolfninja Apr 15 '20 at 11:07
  • You forget the most basic thing you need to remember when dealing with system functions: They can fail! And when they fail they will return a value indicating that failure. In the case of [`getlogin`](http://man7.org/linux/man-pages/man3/getlogin.3.html) it will return a *null pointer*, which of course can't be used to initialize a `std::string` object. Hence the crash. Remember: Always check for failure! – Some programmer dude Apr 15 '20 at 12:32

1 Answers1

3

getlogin() reads the login information from the utmp file, so it won't work if the process isn't associated with a terminal.

I assume from the seteuid call in your example that process A is running with the effective user ID of the original user.

If you don't have a terminal, but have the uid you need to use the "passwd" database (often, but not always, backed by the /etc/passwd file):

struct passwd *pw = getpwuid(geteuid());
string userName = pw->name;
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Mikel Rychliski
  • 3,455
  • 5
  • 22
  • 29