【发布时间】:2021-10-11 20:03:07
【问题描述】:
在为MIT6.s081的实验室写解决方案的时候,遇到了实验室要求在xv6中写bash命令find的问题。
我的代码如下:
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/fs.h"
char* getFmtFile(char *path){
static char buf[DIRSIZ + 1];
char *p;
for(p = path + strlen(path); p >= path && *p != '/'; p--){
;
}
p++;
if(strlen(p) >= DIRSIZ)
return p;
memmove(buf, p, strlen(p));
memset(buf + strlen(p), 0 , DIRSIZ - strlen(p));
return buf;
}
void find(char* dir, char* file){
char buf[512], *p;
int fd;
struct dirent de;
struct stat st;
if(( fd = open(dir, 0)) < 0){
fprintf(2, "find : cannot open %s\n", dir);
return;
}
if(fstat(fd, &st) < 0){
fprintf(2, "find : cannot stat %s\n", dir);
close(fd);
return;
}
//printf("Successfully open director,dir : %s, file : %s\n", dir, file);
switch(st.type){
case T_FILE:
//printf("Current file is %s\n", getFmtFile(dir));
if(strcmp(getFmtFile(dir), file) == 0){
fprintf(1, "%s\n", dir);
}
break;
case T_DIR:
if(strlen(dir) + 1 + DIRSIZ + 1 > sizeof buf){
printf("find : path too long\n");
break;
}
strcpy(buf, dir);
p = buf + strlen(buf);
*p++ = '/';
while(read(fd, &de, sizeof(de)) == sizeof(de)){
//char* cur = getFmtFile(de.name);
char *cur = de.name;
//printf("Current file : %s\n",cur);
if(de.inum == 0 || strcmp(cur, ".") == 0 || strcmp(cur, "..") == 0)
continue;
memmove(p, de.name, DIRSIZ);
p[DIRSIZ] = 0;
if(stat(buf, &st) < 0){
printf("find: cannot state %s\n", buf);
continue;
}
find(buf, file);
//printf("%s %d %d %d\n", getFmtFile(buf), st.type, st.ino, st.size);
//printf("Get out of find\n");
}
break;
}
close(fd);
}
int main(int argc, char *argv[]){
if(argc != 3){
fprintf(2, "Usage: find [directory] [file name]\n");
exit(1);
}
// printf("find %s in %s\n", argv[2], argv[1]);
find(argv[1], argv[2]);
exit(0);
//return 0;
}
在我的概念中,return 0 等于 main function 中的 exit(0)。 bash 派生一个子进程来执行find,当我调用 return 0 时它将退出。但是当我使用 return 而不是退出时似乎出现了问题。
返回后似乎程序没有完成?
【问题讨论】:
-
当您检查
for(p= ...的循环结束时,您可能会将p与path进行比较,而p是path - 1。这不是一个有效的指针。指向一个元素过去对象的指针是一个有效的指针(并且不能被引用),但是一个元素的值before对象甚至不是一个有效的指针。