一 、/etc/passwd
我们发现
ls -l 显示线程的 user名 和 group名
ls -n 显示线程的 user id 和 group id
mhr@ubuntu:~$ ls -l
total 52
drwxr-xr-x 3 mhr mhr 4096 Sep 2 2019 Desktop
drwxr-xr-x 2 mhr mhr 4096 Sep 2 2019 Documents
drwxr-xr-x 2 mhr mhr 4096 Sep 2 2019 Downloads
-rw-r--r-- 1 mhr mhr 8980 Sep 2 2019 examples.desktop
drwxr-xr-x 2 mhr mhr 4096 Sep 2 2019 Music
drwxr-xr-x 2 mhr mhr 4096 Sep 2 2019 Pictures
drwxr-xr-x 2 mhr mhr 4096 Sep 2 2019 Public
drwxrwxr-x 2 mhr mhr 4096 Nov 9 2019 shiyan
drwxr-xr-x 2 mhr mhr 4096 Sep 2 2019 Templates
drwxr-xr-x 2 mhr mhr 4096 Sep 2 2019 Videos
drwxrwxr-x 8 mhr mhr 4096 Apr 16 08:17 work
mhr@ubuntu:~$
mhr@ubuntu:~$
mhr@ubuntu:~$ ls -n
total 52
drwxr-xr-x 3 1000 1000 4096 Sep 2 2019 Desktop
drwxr-xr-x 2 1000 1000 4096 Sep 2 2019 Documents
drwxr-xr-x 2 1000 1000 4096 Sep 2 2019 Downloads
-rw-r--r-- 1 1000 1000 8980 Sep 2 2019 examples.desktop
drwxr-xr-x 2 1000 1000 4096 Sep 2 2019 Music
drwxr-xr-x 2 1000 1000 4096 Sep 2 2019 Pictures
drwxr-xr-x 2 1000 1000 4096 Sep 2 2019 Public
drwxrwxr-x 2 1000 1000 4096 Nov 9 2019 shiyan
drwxr-xr-x 2 1000 1000 4096 Sep 2 2019 Templates
drwxr-xr-x 2 1000 1000 4096 Sep 2 2019 Videos
drwxrwxr-x 8 1000 1000 4096 Apr 16 08:17 work
mhr@ubuntu:~$
但我们自己实现 ls 系列命令的时候,需要使用 user名 和 group名,user id 和 group id 等信息,那这些信息存储在什么位置呢? 在 linux,unix系统中 这些信息存储在 /etc/passwd 中而在 FreeBSD系统上,这些信息存储在一个数据库中。在HPUnix系统中,这些信息存储在文件系统中。
mhr❌1000:1000:MHR,:/home/mhr:/bin/bash,
所以在 unix,linux 系统中 可以查找 /etc/passwd文件中的对应用户名或di 等信息。
那么各个系统 存储 上述信息的位置不一样,用户使用就比较麻烦,所以就有了标准,标准就出来和稀泥了~
标准说:既然你们对这些信息的存储的实现都不一样,那么我就统一一下标准实现吧。
getpwuid()
getpwnam()
NAME
getpwnam, getpwnam_r, getpwuid, getpwuid_r - get password file entry
通过 uid 或者 user name 来查询用户信息。
SYNOPSIS
#include <sys/types.h>
#include <pwd.h>
struct passwd *getpwnam(const char *name);
struct passwd *getpwuid(uid_t uid);
The passwd structure is defined in <pwd.h> as follows:
struct passwd {
char *pw_name; /* username */
char *pw_passwd; /* user password */
uid_t pw_uid; /* user ID */
gid_t pw_gid; /* group ID */
char *pw_gecos; /* user information */
char *pw_dir; /* home directory */
char *pw_shell; /* shell program */
};
注意不同系统的 passed 中的字段可能不一样,具体需要看手册!
实验1 :使用 getpwuid() 获取 passwd相关信息
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <pwd.h>
int main(int argc,char *argv[])
{
struct passwd *pwdline;
if(argc < 2)
{
fprintf(stderr,"Usage:%s <src_file> <dest_file>\n",argv[0]);
exit(1);
}
//atoi() : string --> int 转换
pwdline = getpwuid(atoi(argv[1]));
//puts string 打印用户名,打印字符换 直接而用 puts()
puts(pwdline->pw_name);
exit(0);
}
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/27$ gcc getpwuid.c
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/27$
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/27$ ./a.out 1000
mhr //我自己
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/27$
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/27$
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/27$ ./a.out 0
root // uid 为0 是 root 用户
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/27$