20165223 《信息安全系统设计基础》 实现mybash

一、学习pwd命令

1. pwd命令简介

  • 英文原名:Print Working Directory
  • 指令功能:打印出当前工作目录
  • 执行权限:All User
  • 指令所在路径:/usr/bin/pwd 或 /bin/pwd

2. pwd命令基本语法

  • pwd [OPTION]

3. pwd命令参数

选项 描述
-L (即逻辑路径logical ) 使用环境中的路径,即使包含了符号链接
-P (即物理路径physical) 避免所有的符号链接
–help 显示帮助并退出
–version 输出版本信息并退出

4. pwd命令退出状态

返回值 状态
0 成功
非零值 失败

二、研究pwd实现需要的系统调用(man -k; grep)并写出伪代码

1. 实现pwd需要的系统调用

(1)先用man -k directory | gerp 2来查看一下是否有可用命令

(2)发现命令getcwd符合找到当前目录的要求

  • 使用man getcwd查看系统调用

  • 找到需要的头文件和函数参数
#include <unistd.h>

char *getcwd(char *buf, size_t size);

(3) 同时还需要用到chdir,来改变当前目录

  • 使用man chdir查看系统调用

  • 找到需要的头文件和函数参数
#include <unistd.h>

int chdir(const char *path);

(4)命令readdir也符合要求,用于打开并读取当前目录文件

  • 使用man readdir查看系统调用

扫描二维码关注公众号,回复: 4225716 查看本文章

  • 找到需要的头文件和函数参数
#include <dirent.h>

struct dirent *readdir(DIR *dirp);

int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);

2. 伪代码

(1)用“.”获取当前目录的i-node(inode)
(2)用“..”获取父级目录的i-node(up_inode)
(3)判断当前目录的i-node和父级目录的i-node是否相同
(4)相同:到达根目录,输出完整路径,退出程序
(5)不同:还未到根目录,切换至父级目录,返回(1)再次执行相同操作直至两个i-node相同

三、实现mypwd

#include<stdio.h>  
#include<sys/stat.h>  
#include<dirent.h>  
#include<stdlib.h>  
#include<string.h>  
#include<sys/types.h> 
#include <unistd.h> 
void printpath();  
char *inode_to_name(int);  
int getinode(char *);  
//功能:打印当前目录路径
void printpath()  
{  
    int inode,up_inode;  
    char *str;
    inode = getinode(".");  
    up_inode = getinode("..");  
    chdir("..");  
    str = inode_to_name(inode);  
    //当当前目录的i-node与父级目录的i-node相同时,到达根目录
    if(inode == up_inode) {  
        return;  
    }  
    //打印路径
    printpath();  
    printf("/%s",str);  
}  
//功能:获取当前目录的i-node
int getinode(char *str)  
{  
    struct stat st;  
    if(stat(str,&st) == -1){  
        perror(str);  
        exit(-1);  
    }  
    return st.st_ino;  
}  
//功能:获取当前路径
char *inode_to_name(int inode)  
{  
    char *str;  
    DIR *dirp;  
    struct dirent *dirt;  
    if((dirp = opendir(".")) == NULL){  
        perror(".");  
        exit(-1);  
    }  
    while((dirt = readdir(dirp)) != NULL)  
    {  
        if(dirt->d_ino == inode){  
            str = (char *)malloc(strlen(dirt->d_name)*sizeof(char));  
            strcpy(str,dirt->d_name);  
            return str;  
        }  
    }  
    perror(".");  
    exit(-1);  
}  
//主函数
int main()  
{  
    printpath();  
    putchar('\n');  
    return 0;  
}

四、测试mypwd

  • 测试截图,成功

  • 用pwd命令检测,一致

猜你喜欢

转载自www.cnblogs.com/moddy13162201/p/10015662.html
今日推荐