我正在制作一个命令外壳,我正在尝试使用“|”实现管道和重定向“>”表示将使用 execv 执行的命令。我坚持尝试实施“>”并遇到段错误。 在阅读命令并解释它之后,我用来从命令行读取输入的代码是:
//this is the while loop I am using to seperate the command line input
//stored in the variable line( retrieved using getline)
//delim here is a whitespace
while((temp=strsep(&line,delim)+'\0')!=NULL)
//these are the kinds of statements I am using to store them in the
//**char global array: input
i++;
input=realloc(input,i*sizeof(char*));
input[i-1]=temp;
//I used realloc here because the input function reads input until it //encounters "\n",";" or">" and eventually "|"
//these lines are where I think my problem begins
else if(strncmp(temp,">",1)==0)
{
redirect=1;
continue;
}
//redirect is a global integer with initial value 0
//I change it to 1, so that the function can use that information to direct
//output to another file
if(redirect==1)
{
if(temp[strlen(temp)-1]=='\n')
{
temp[strlen(temp)-1]=0;
}
filename=temp;
break;
}
//this is the code in the input reading function that also reads the //filename to redirect output to in the global char* 'filename'
//this happens in the child process
if(pid==0)
{
if(redirect==1)
{
int file=open(filename, O_WRONLY | O_CREAT, 0777);
if(file==-1)
{
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
breakptr=1;//this tells the main loop that an error has occured
return;
}
int file2= dup2(file, STDOUT_FILENO);
close(file);
redirect=0;
}
if(execv(found,input)==-1)
.
.
.
}
当这段代码执行时,我遇到了段错误,如果不是这样,那么 bin/ls 将工作一次,然后就完全不工作了。我需要帮助找出我哪里出错了,以及是否有更好的方法来完成这个。
我尝试更改命令循环,最初我检查函数中的整个输入字符串,我在其中为“>”或“|”分叉进程人物。我在该实施中遇到了类似的问题。我还尝试检查互联网和堆栈溢出以获取类似实现的想法,但他们中的大多数人都使用了这种方法,并且对他们来说效果很好。 我还怀疑文件名变量可能会导致问题,因为它是堆栈上动态分配的字符数组,仅在某些情况下?