Subscribe to the RSS Feed


getlogin vs getpwuid

getlogin (2):

The getlogin() routine returns the login name of the user associated with the current session, as previously set by setlogin(). The name is normally associated with a login shell at the time a session is created, and is inherited by all processes descended from the login shell. (This is true even if some of those processes assume another user ID, for example when su(1) is used).

getpwuid (3):

The functions getpwnam() and getpwuid() search the password database for the given login name or user uid, respectively, always returning the first one encountered.

One can get the current username using getpwuid with the following code:

struct passwd *tmp;
tmp = getpwuid(getuid());
printf(“username: %s\n”, tmp->pw_name)

Also note getpwuid_r (3) which is the thread safe version of the above.

Why is it better using getpwuid than getlogin? Imagine you are setting up a chrooted/jailed environment. getpwuid will always give back consistent results, while getlogin will tell different credentials if jexec/su/sudo is used.

Posted 2009/11/17 11:28 by alex


Leave a Comment

Add your comment. Preview then Submit.


Textile Help