我使用 C 编写自己的 shell 并处理流重定向(">" 和 "<") 我使用 strtok() 来获取它们并存储相关信息以供稍后在程序中使用。我不确定为什么在第一次调用时会出现分段错误。(目前代码非常混乱)。
#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++;
}
}
}
}