It is possible that single user id in passwd file can map to different entries with different login name. getlogin system call can return the current login name.
Definition:
ubuntu@ip-172-31-23-227:~$ less /usr/include/unistd.h
......
/* Return the login name of the user.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern char *getlogin (void);
......
2. Example:
record.c:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pwd.h>
int main(int argc, char* argv[])
{
char *login;
// Retrieve and output the login name
if((login = getlogin()) == NULL) {
printf("getlogin error!\n");
exit(1);
}
printf("%s\n", login);
// Retrieve the passwd record based on login name
struct passwd *pw;
if((pw = getpwnam(login)) == NULL) {
printf("getpwnam error!\n");
exit(2);
}
printf("Username: %s, Password: %s, User ID: %d, Group ID: %d, \n",
pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid);
printf("realname: %s, home dir: %s, shell: %s\n", pw->pw_gecos, pw->pw_dir, pw->pw_shell);
exit(0);
}
shell:
After getting the current login name with "getlogin()", then we use getpwnam to retrieve the password record from passwd file based on retrieved login name.
ubuntu@ip-172-31-23-227:~$ ./record.out
ubuntu
Username: ubuntu, Password: x, User ID: 1000, Group ID: 1000,
realname: Ubuntu, home dir: /home/ubuntu, shell: /bin/bash
No comments:
Post a Comment