UNIX环境高级编程之第6章:系统数据文件跟信息

UNIX环境高级编程之第6章:系统数据文件和信息

6.1 引言

UNIX系统的正常运行需要使用大量与系统有关的数据文件,例如,口令文件/etc/passwd和组文件/etc/group就是经常被多个程序频繁使用的两个文件。用户每次登陆UNIX系统,以及每次执行ls -l命令是都要使用口令文件。
对于这些数据文件的可移植接口是本章的主题。本章包括了系统标示函数、时间、日期函数。

6.2 口令文件(Password File)

给出用户登录名或数值用户ID后,这两个用户就可以查看相关项
#Include <pwd.h>
struct passwd *getpwuid(uid_t uid);
struct passwd *getpwnam(const char *name);
getpwuid函数由ls(1)程序使用,在输入登录名是,getpwnam函数由login(1)程序使用

下列函数可以用来查看整个口令文件
#include<pwd.h>
struct passwdd *getpwent(void);
void setpwent(void);
void endpwent(void);
调用getpwent时,它返回口令文件中的下一个纪录项
函数setpwent反绕它所使用的文件,endpwent则关闭这些文件。
使用getpwent查看完口令文件后,一定要调用endpwent关闭这些文件

getpwnam函数的一个实现
#include <pwd.h>
#include <stddef.h>
#include <string.h>
struct passwd *getpwnam(const char *name)
{
      struct passwd *ptr;
      setpwent();
      whlie((ptr = getpwent())!=NULL)
            if(strcmp(name,ptr->pw_name)==0)
                     break;
      endpwent(); 
      return(ptr);
}

setpwent反绕有关文件使它们定位到文件开始处(自我保护措施)。getpwnam和getpwuid完成后不应使文件处于打开状态,所以调用endpwent关闭它们。

6.3 阴影口令(Shadow Passwords)

某些系统讲加密口令存放在另一个通常称为阴影口令的文件中。该文件至少包含用户名和加密口令。与该口令相关的其他信息也可以存放在该文件中。

阴影口令文件不应是一般用户可以读取的。仅有少数几个程序需要访问加密口令,如login(1)和passwd(1)。有了阴影口令普通口令文件/etc/passwd可以让用户自由读取了

有另一组函数可用于访问阴影口令文件
#include <shadow.h>
struct spwd *getspnam(const char *name);
struct spwd *getspent(void);
void setpent(void);
void endspent(void);

6.4 组文件

用下列函数来查看组名或数值组ID
#include <grp.h>
struct group *getgrgid(gid_t gid);
struct group *gergrnam(const char *name);

如同对口令文件进行操作的函数一样

如果需要搜索整个组文件,则必须使用另外几个函数
#include <grp.h>
struct group *getgrent(void);
void setgrent(void);
void endgrent(void);

6.5 附属组ID

6.6 实现区别

6.7 其他数据文件

至此讨论了两个系统数据文件-口令文件和组文件。UNIX系统还使用很多其他文件。例如,网络服务器所提供服务的数据文件(/etc/services),记录协议信息的数据文件(/etc/protocols),这写数据文件的接口都与上述对口令文件的组文件的相似
分别是get函数(读下一个记录),set函数(反绕该文件,希望在相应文件起始处开始处理),end函数(关闭相应数据文件)

6.8 登录账户记录

utmp文件记录当前登录到系统的各个用户;wtmp文件跟踪各个登陆和注销事件

版权声明:本文为博主原创文章,未经博主允许不得转载。