PWD的编译及调试

时间:2023-03-09 08:13:13
PWD的编译及调试

实现mypwd

1 学习pwd命令

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

3 实现mypwd

4 测试mypwd


Linux命令学习:pwd命令

该命令用来显示目前所在的工作目录。指令英文原义:print work directory

执行权限    :All User

指令所在路径:/usr/bin/pwd 或 /bin/pwd
命令语法:

pwd [OPTION]...

命令参数:

参数 长参数 描叙
-L --logical(无效) 当目录为连接路径时,显示连接路径
-P --physical(无效) 显示实际物理路径,而非使用连接(link)路径

查看pwd命令的帮助信息

root@DB-Server init.d]# man pwd
PWD(1) User Commands PWD(1) NAME
pwd - print name of current/working directory SYNOPSIS
pwd [OPTION]... DESCRIPTION
Print the full filename of the current working directory. -L, --logical
use PWD from environment, even if it contains symlinks -P, --physical
avoid all symlinks --help display this help and exit --version
output version information and exit NOTE: your shell may have its own version of pwd, which usually supersedes the version described here. Please refer to your shell鈥檚 documentation for details about the
options it supports. AUTHOR
Written by Jim Meyering. REPORTING BUGS
Report bugs to <bug-coreutils@gnu.org>. COPYRIGHT
Copyright 2006 Free Software Foundation, Inc.
This is free software. You may redistribute copies of it under the terms of the GNU General Public License <http://www.gnu.org/licenses/gpl.html>. There is NO WARRANTY, to
the extent permitted by law. SEE ALSO
The full documentation for pwd is maintained as a Texinfo manual. If the info and pwd programs are properly installed at your site, the command info pwd should give you access to the complete manual. pwd 5.97 PWD(1)
(END)

PWD代码如下:

include
include<sys/stat.h>
include
include
include
include<sys/types.h>
void printpath();
char inode_to_name(int);
int getinode(char );
int main()
{
printpath();
putchar('\n');
return ;
}
void printpath()
{
int inode,up_inode;
char str;
inode = getinode(".");
up_inode = getinode("..");
chdir("..");
str = inode_to_name(inode);
if(inode == up_inode) {
// printf("/%s",str);
return;
}
printpath();
printf("/%s",str);
}
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);
}

截图如下:

PWD的编译及调试