《Unix环境高级编程》之 系统数据文件和时间处理函数

来源:互联网 发布:绝对伏特加 知乎 编辑:程序博客网 时间:2024/06/05 05:37

  Unix系统的正常运行需要使用大量与系统有关的数据文件,如口令文件/etc/passwd和组文件/etc/group,本章主要介绍访问这些系统文件的可移植接口以及处理时间的函数。

  1. 口令文件
      口令文件存储在/etc/passwd中,而且是一个ASCII文件,在Linux中,口令文件包含字段有:用户名:加密口令:数值用户ID:数值组ID:注释字段:初始工作目录:初始shell。登录项用冒号分割,如:root:x:0:0:root:/root:/bin/bash
    关于登录项要注意以下几点:

    • 有一个用户名为root的登录项,其用户ID是0(超级用户);
    • 加密口令一般存在另一个文件中,所以用占位符“x”表示;
    • 某些字段可能为空;
    • shell字段包含一个可执行程序名,它被用作该用户的登录shell,若该字段为空,则取系统默认名,通常为/bin/sh;
    • 为阻止特定用户登录系统,可使shell字段为/bin/false、/bin/true、/bin/nologin。

    POSIX.1定义了两个获取口令文件的函数:

    #include <pwd.h>struct passwd *getpwuid(uid_t uid);struct passwd *getpwnam(const char* name);返回值:成功则返回指针,出错返回NULL

      这两个函数都返回执行passwd结构的指针,passwd结构通常是相关函数内的静态变量,只要调用该函数,其值就会被改写。
    读取整个口令文件的函数:

    #include <pwd.h>struct passwd* getpwent(void);返回值:成功则返回指向passwd结构的指针,出错或到达文件尾返回NULL;void setpwent(void);void endpwent(void);

      getwent查看口令文件中的下一个记录,setpwent反绕口令文件,即回到文件开始处,endpwent关闭口令文件,第一次调用getpwent打开口令文件,最后一定要关闭
      某些系统将加密口令存储在另一个称为阴影口令的文件中,该文件为/etc/shadow,在Linux中,存在一组与访问口令文件类似的函数来访问阴影口令文件。

  2. 组文件
    Unix组文件包含的字段有:组名(char gr_name),加密口令(char gr_passwd),数组组ID(int gr_id),指向各用户名的指针的数组(char ** gr_mem)。
    gr_mem是一个指针数组,其每一个成员指向一个属于该组的用户名。

  3. 系统标识
    POSIX.1定义了uname函数,它返回与当前主机和操作系统有关的信息。

    #include <sys/utsname.h>int uname(struct utsname* name);返回值:若成功返回非负值,出错返回-1struct uname{char sysname[]; //操作系统名char nodename[];char release[]; char version[]; //当前系统的发行版本号char machine[]; //硬件类型  }

    utsname结构的信息可以用uname命令打印。

  4. 时间和日期函数
    Unix内核提供的基本时间服务是计算自国际标准时间公元1970年1月1日00:00:00以来经过的秒数。内核以time_t结构来表示,一般称作日历时间。

    #include <time.h>time_t time(time_t * calptr);返回值:成功则返回时间值,出错返回-1

    时间值总是做为函数值返回,若参数不为空,则时间值也存放在参数中。
    gettimeofday返回更精确的时间信息

    #include <sys/time.h>int gettimeofday(struct timeval *restrict tp, void * restrict tzp);返回值:总是0struct timeval{      time_t  tv_sec;   //秒数      long  tv_usec;   //微秒数}

      一旦取得以秒为单位的整型时间值后,便可以调用另一些函数将其转换为人们可读的时间和日期,下图显示了各种时间函数之间的关系:
      这里写图片描述

    #include <time.h>struct tm* gmtime(const time_t * calptr);struct tm* localtime(const time_t* calptr);返回值:指向tm结构的指针这两个函数将日历时间转换为以年、月、日、时、分、秒、周表示的时间,localtime转换为本地时间,gmtime转换为国际标准时间。struct tm{    int tm_sec;  //[0-60]    int tm_min; //[0-59]    int tm_hour;    int tm_mday;    int tm_mon;    int tm_year;    int tm_wday;    int tm_yday;    int tm_isdst;}#include <time.h>time_t mk_time(struct tm* tmptr);返回值:成功则返回日历时间,出错返回-1;mk_time将tm结构的时间转换为日历时间#include<time.h>char* astime(const struct tm* tmptr);char* ctime(const struct tm* calptr);返回值:指向以null结尾的字符串的指针;这两个函数产生熟悉的26字节的字符串,与date命令的输出形式类似。#include <time.h>size_t strftime(char * restrict buf, size_t maxsize, const char* restrict format, const struct tm* restrict tmptr);返回值:若有空间则返回存入数组的字符数,否则返回0
阅读全文
0 0