【发布时间】:2011-03-05 22:04:48
【问题描述】:
我正在使用 C 编写自己的 shell 并处理流重定向(">" 和 "
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
int main (){
char *command, *mypath, *buffer, *arglist[1024], *pathlist[1024],
**ap, *carrotfile1, *carrotfile2;
char* tokenPtr = malloc(1024);
buffer = malloc(1024);
carrotfile1 = malloc(1024);
carrotfile2 = malloc(1024);
int loop = 1, code = 0, fail = 0;
while (loop == 1){
int argnum = 0, pathnum = 0;
mypath = malloc(1024);
if(getenv("MYPATH") == NULL)
strcpy(mypath, "/bin#.");
else
strcpy(mypath, getenv("MYPATH"));
printf("myshell$ ");
command = readline("");
if(strcmp(command, "exit") == 0 || strcmp(command, "quit") == 0)
return 0;
if(strcmp(command, "") == 0)
continue;
/*Tokenizes Command*/
/*
Code 1: > is present
Code 2: < is present
Code 3: Both Present
*/
printf("seg?\n");
tokenPtr = strtok(command, " "); /*Segfaults this line...*/
printf("tokenPtr: %s", tokenPtr);
while(tokenPtr != NULL){
if(strcmp(tokenPtr, ">") == 0){
if(code == 0)
code = 1;
else if(code == 2)
code = 3;
else{
printf("Error: Cannot have multiple equivalent redirects\n");
fail = 1;
}
tokenPtr = strtok(NULL, " ");
strcpy(carrotfile1,tokenPtr);
tokenPtr = strtok(NULL, " ");
strcpy(arglist[argnum], tokenPtr);
argnum++;
}
else if (strcmp(tokenPtr,"<") == 0){
if(code == 0)
code = 2;
else if(code == 1)
code = 3;
else{
printf("Error: Cannot have multiple equivalent redirects\n");
fail = 1;
}
tokenPtr = strtok(NULL, " ");
strcpy(carrotfile2, tokenPtr);
tokenPtr = strtok(NULL, " ");
strcpy(arglist[argnum], tokenPtr);
argnum++;
}
else{
tokenPtr = strtok(NULL, " ");
strcpy(arglist[argnum], tokenPtr);
argnum++;
}
}
}
}
【问题讨论】:
-
请注意code samples 应该是完整的(上面是)并且简洁(不是)。尽管方式不同,但这对所有相关人员都有好处。
-
出于好奇,这个是功课,自学,是你自己想用的还是你希望发布的?
-
谢谢,下次我会记住这一点。这是操作系统类问题的第二部分(第一部分是使用 PATH 查找和运行具有可变数量参数的命令)。我的第一部分和后台进程也在工作,流重定向是最后一部分。解析后,我知道如何关闭子进程中的文件描述符以使其正常工作。我可能会在此处发布完整的代码,以供寻找好示例的人使用(一旦我对其进行了一些重构)。
-
@outis strncpy 很糟糕,因为它 a)不一定 NUL 终止结果,b)毫无意义地 NUl 填充结果。而且 strlcpy 不是标准 C。请参阅最近关于 SO 的讨论。
标签: c pointers operating-system segmentation-fault strtok