LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 607|回复: 1

怎么可以得到uid所对应的用户的字符串啊?

[复制链接]
发表于 2005-4-27 12:47:49 | 显示全部楼层 |阅读模式
比如说uid=0的时候是root,那么root这个字符串从哪里得到?
task_struct里有么?好像task_struct里只有uid啊
哪位高手知道,先谢了
发表于 2005-4-27 13:16:22 | 显示全部楼层
信息是保存在/etc/passwd文件中的,
#include <sys/types.h>
#include <pwd.h>
struct passwd *getpwuid(uid_t uid);
struct passwd *getpwnam(const char *name);
The password database structure, passwd, defined in pwd.h includes the following members:
passwd Member Description
char *pw_name The user’s login name
uid_t pw_uid The UID number
gid_t pw_gid The GID number
char *pw_dir The user’s home directory
char *pw_gecos The user’s full name
char *pw_shell The user’s default shell
Some UNIX systems may use a different name for the field for the user’s full name: on some systems, it’s
pw_gecos, as on Linux, and on others, it’s pw_comment. This means that we can’t recommend its use.
The getpwuid and getpwnam functions both return a pointer to a passwd structure corresponding to a
user. The user is identified by UID for getpwuid and by login name for getpwnam. They both return a
null pointer and set errno on error.
Try It Out—User Information
Here’s a program, user.c, which extracts some user information from the password database:
#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
#include <unistd.h>
156
Chapter 4
int main()
{
uid_t uid;
gid_t gid;
struct passwd *pw;
uid = getuid();
gid = getgid();
printf(“User is %s\n”, getlogin());
printf(“User IDs: uid=%d, gid=%d\n”, uid, gid);
pw = getpwuid(uid);
printf(“UID passwd entry:\n name=%s, uid=%d, gid=%d, home=%s, shell=%s\n”,
pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw->pw_shell);
pw = getpwnam(“root”);
printf(“root passwd entry:\n”);
printf(“name=%s, uid=%d, gid=%d, home=%s, shell=%s\n”,
pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw->pw_shell);
exit(0);
}
It gives the following output, which may differ in minor respects between versions of Linux and UNIX:
$ ./user
User is neil
User IDs: uid=500, gid=100
UID passwd entry:
name=neil, uid=500, gid=100, home=/home/neil, shell=/bin/bash
root passwd entry:
name=root, uid=0, gid=0, home=/root, shell=/bin/bash
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表