一个简单的pwd,segfault了

haolly 2013-10-20 12:27:04
看书上代码写的,可是一运行就出现 Segmentation fault

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUFSIZE NAME_MAX
ino_t get_inode(char*);
void printpathto(ino_t);
void inum_to_name(ino_t,char*,int);
int main(int argc, char** argv)
{
printpathto(get_inode("."));
putchar('\n');
return 0;
}
ino_t get_inode(char* filename)
{
struct stat info;
if(stat(filename,&info)==-1)
{
fprintf(stderr,"Cannot stat");
perror(filename);
exit(1);
}
return info.st_ino;
}
void printpathto(ino_t this_node)
{
ino_t my_inode;
char its_name[BUFSIZE];
if(get_inode("..")!=this_node); //if this is not root
{
inum_to_name(this_node,its_name,BUFSIZE);
chdir("..");
my_inode=get_inode(".");
printpathto(my_inode); //recursive print
printf("/%s",its_name);
}
}
void inum_to_name(ino_t inode_to_find, char* namebuf, int bufsize)
{
DIR* dir_ptr;
struct dirent * direntp;
dir_ptr=opendir(".");
if(dir_ptr==NULL)
{
perror(".");
exit(1);
}
while((direntp=readdir(dir_ptr))!=NULL)
{
if(direntp->d_ino == inode_to_find)
{
strncpy(namebuf, direntp->d_name, bufsize);
namebuf[bufsize-1] = '\0'; //just in case
closedir(dir_ptr);
return ;
}

}
fprintf(stderr, "error looking for inum %d\n",(int)inode_to_find);
exit(1);

}
...全文
121 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
JoeBlackzqq 2013-10-28
  • 打赏
  • 举报
回复
有分号的情况我测了下,是死循环!!!! 加几个打印就知道了,一直不停地在打印信息!
JoeBlackzqq 2013-10-28
  • 打赏
  • 举报
回复
引用 2 楼 Idle_Cloud 的回复:
你这个程序也太夸张了吧, if(get_inode("..")!=this_node); 这句结尾居然一个分号,递归太多了,早堆栈溢出了。
兄台好眼力啊! 根据你的指示,把那里的分号去掉后,运行结果为:

[zcm@t1 #45]$make
gcc -g -o a a.c
[zcm@t1 #46]$./a
/././././.
ckc 2013-10-28
  • 打赏
  • 举报
回复
楼上的,if只执行一次,就算后面直接分号也不会递归什么的吧 不过if后面直接分号基本上可以认为程序这里是出错了,楼主先检查一下
Carl_CCC 2013-10-28
  • 打赏
  • 举报
回复
你这个程序也太夸张了吧,
if(get_inode("..")!=this_node);
这句结尾居然一个分号,递归太多了,早堆栈溢出了。
haolly 2013-10-28
  • 打赏
  • 举报
回复
引用 2 楼 Idle_Cloud 的回复:
你这个程序也太夸张了吧, if(get_inode("..")!=this_node); 这句结尾居然一个分号,递归太多了,早堆栈溢出了。
这是用眼睛看出来的(⊙_⊙)? 我是不是该锻炼一下自己的眼力
haolly 2013-10-28
  • 打赏
  • 举报
回复
引用 4 楼 JoeBlackzqq 的回复:
[quote=引用 2 楼 Idle_Cloud 的回复:] 你这个程序也太夸张了吧, if(get_inode("..")!=this_node); 这句结尾居然一个分号,递归太多了,早堆栈溢出了。
兄台好眼力啊! 根据你的指示,把那里的分号去掉后,运行结果为:

[zcm@t1 #45]$make
gcc -g -o a a.c
[zcm@t1 #46]$./a
/././././.
[/quote] 将36行和37行互换之后就可以了。 在自己的目中中找 . 所对应的i节点所对应的名字,只能得到 .
haolly 2013-10-27
  • 打赏
  • 举报
回复
大神指导啊

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧