20155239 2017-11-19 实现mypwd(选做,加分)

20155239 2017-11-19 实现mypwd(选做,加分)

题目和要求

  • 学习pwd命令
  • 研究pwd实现需要的系统调用(man -k; grep),写出伪代码
  • 实现mypwd
  • 测试mypwd

首先需要了解的问题:

问题一:该命令的作用和全名称是什么?

print work directoryPWD)该命令用来显示目前所在的工作目录。执行权限面对所有的用户。指令所在路径:/usr/bin/pwd 或 /bin/pwd

问题二:该命令的参数有哪些?

如图:

问题三:什么是系统调用?

由操作系统实现提供的所有系统调用所构成的集合即程序接口或应用编程接口(ApplicationProgrammingInterface,API)。是应用程序同系统之间的接口。用户在程序的中调用操作系统中的功能子模块。

问题四:man命令的使用和作用?

刚刚学习到Linux的时,通常需要使用man 命令查阅一些命令的帮助信息。一般使用“man 命令名称”的格式就能进行简单的查询。

man -K:显示关键字数据库中包含与作为最终参数给定的字符匹配的标题的字符串的每一行。 可以输入多个标题,中间用空格隔开。 要使用 -k 标志,root 用户必须以前已输入 catman -w 以建立 /usr/share/man/whatis 文件。

包括man的其他主要参数查资料如下:

1. -c

显示使用 cat 命令的手册信息。

2. -t

使用 troff 命令格式化手册信息。如果在超文本信息基中查找到手册页面,则忽略该标志。

3.-f

显示在关键字数据库中仅与作为最终参数给定的命令名相关的项。可以输入多个命令名,中间用空格隔开。使用该标志仅搜索命令物件。要使用 -f 标志,root 用户必须以前已输入catman-w以建立/usr/share/man/whatis 文件。

4.-F

只显示首个匹配项。

5、-m

只在 MANPATH 或 -M 中指定的路径中搜索。

执行pwd命令可立刻得知您目前所在的工作目录的绝对路径名称

测试代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    int main(){
     char *filepath=NULL;
     filepath=getcwd(NULL,0);
     puts(filepath);
     free(filepath);
     return 0;
   }

如图:

PWD需要实现的系统调用

  1. man -k pwd:没有找到任何系统调用

  2. man -k current directory:以pwd的描述作为关键字进行查找

  3. man -k current directory | grep 2:筛选系统调用命令,有一个叫做getcwd的系统调用

系统调用命令:Getcwd

pwd打印的是绝对路径,直至根目录

伪代码:

void get_file_name(*filepath){
  获取当前i-Node;
  通过i-Node获取当前路径名称filepath(%s);

   cd ..;
  获取当前i-Node;
  通过i-Node获取当前路径名filepath称(%s);
   get_file_name(*filepath);
  if(..i-Node == . i-Node){
  return;
  }
   printf('/'+filename);
  return;
}

测试代码:

 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <dirent.h>
 #include <pwd.h>
  ino_t get_inode(char *);
  void printpathto(ino_t);
  void inum_to_name(ino_t, char *, int);

  int main() {
 printpathto(get_inode(".")); /* print path to here */
 putchar('\n'); /* then add newline */
 return 0;
}

/*
 *        prints path leading down to an object with this inode
 * kind of recursive
*/
void printpathto(ino_t this_inode) {
ino_t my_inode;
char its_name[BUFSIZ];
if (get_inode("..") != this_inode) {
    chdir(".."); /* up one dir */
    inum_to_name(this_inode, its_name, BUFSIZ);/* get its name*/
    my_inode = get_inode("."); /* print head */
    printpathto(my_inode); /* recursively */
    printf("/%s", its_name); /* now print name of this */
  }
}
void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen) {
DIR *dir; 
struct dirent *direntp; 
dir = opendir(".");

 while ((direntp = readdir(dir)) != NULL)
    if (direntp->d_ino == inode_to_find) {
        strncpy(namebuf, direntp->d_name, buflen);
        namebuf[buflen - 1] = '\0'; 
        closedir(dir);
        return;
    }

  exit(1);

}


 ino_t get_inode(char *filename) {   //返回文件的i-Node值
struct stat file;

if (stat(filename, &info) == -1) {
    perror(fname);
    return 1;
}
return file.st_ino;
}

posted on 2017-11-19 15:19  吕宇轩  阅读(209)  评论(0编辑  收藏  举报