我怎样才能使我自己的命令shell的管道工作?

envsm3lx  于 2023-02-24  发布在  Shell
关注(0)|答案(1)|浏览(103)

我正在制作一个命令shell,尝试使用“|“和“〉”表示将使用execv执行的命令。我一直在尝试实现“〉”,并且遇到了seg错误。在阅读命令并解释之后,我用于从命令行读取输入的代码是:

//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)
.
.
.
}

当这段代码执行时,我得到了segfaults,如果不是这样,bin/ls将工作一次,然后就完全不工作了。我需要帮助来找出我哪里出错了,以及是否有更好的方法来完成这一点。
我尝试更改命令循环,最初我检查函数中的整个输入字符串,在该函数中,我为'〉'或'|'字符。我在那个实现中遇到了类似的问题。我也试着检查互联网和堆栈溢出,以获得类似的实现的想法,但他们大多数人使用这种方法,它对他们来说工作得很好。我还怀疑文件名变量可能会导致问题,因为它是堆栈上的字符数组,是动态分配的,只有在某些情况下?

khbbv19g

khbbv19g1#

我看不出“找到”和“输入”是什么。根据Linux页面“int execv(const char *path,char *const argv[]);“。因此这可能是execv(“usr/bin/cat”,{“cat”,“NULL”})。第二个参数(二维字符串,在您的情况下为“input”)需要以空终止。
也可以把printf放在代码的不同位置,让我们知道它在哪里出现了segfault

相关问题