LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Getting uid and/or username of logged in user (https://www.linuxquestions.org/questions/programming-9/getting-uid-and-or-username-of-logged-in-user-233701/)

rjstephens 09-22-2004 02:36 AM

Getting uid and/or username of logged in user
 
Hi
I am writing a C++ app and i need a way to get the the user ID and the user name of the currently logged in user. Any ideas?

(BTW, this is on linux)

Cedrik 09-22-2004 03:34 AM

man utmp ;)

rjstephens 09-22-2004 03:38 AM

thanks.

rjlee 09-22-2004 03:41 AM

If you mean that you want the username and ID of the user who is running the program, you can use
Code:

#include <unistd.h>
#include <sys/types.h>

uid_t uid getuid(void);

You can pass this uid value to getpwdnam to return a structure representing the password file entry:
Code:

#include <pwd.h>
#include <sys/types.h>

struct passwd pw *getpwuid(uid);

And then read out the username with the pw_name field pointed to by pw.

You can also get the username of the current user (which may or may not be either the logged in user or the user running the process; see su -m) using
Code:

#include <stdlib.h>

char * uname = getenv("USER");

I hope that's legible,

— Robert J. Lee

rjstephens 09-22-2004 03:50 AM

thankyou rjiee, I am using:
Code:

#include <unistd.h>

int uid = getuid();

That appears to work. "void" gives a parser error for some reason (I'm using g++). I'll get to the user name stuff later, I don't need that just yet.


Cedrik, thanks but I was just searching on google for details of how to get that to work. Couldn't find any, then I saw rjiee suggestion. Thanks anyway.

rjlee 09-23-2004 05:02 PM

void is only allowed in function prototypes in C or C++. It just means that no parameter is allowed (and can sometimes be omitted).


All times are GMT -5. The time now is 08:15 PM.