I am making a command shell where I am trying to implement piping and redirection using "|" and ">" for commands that will be executed using execv. I am stuck on trying to implement ">" and am getting seg faults. The code that I am using to read input from the command line after reading the command and interpreting it is:
//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)
.
.
.
}
when this code executes, I get segfaults, and if not that, then bin/ls will work once and then not at all. I need help figuring out where I am going wrong, and if there's a better way to accomplish this.
I tried changing the command loop, and initially I was checking the entire input string in the function where I forked the processes for '>' or'|' characters. I faced similar issues in that implementation. I also tried checking the internet, and stack overflow for similar implementations to get ideas from but most of them used this method, and it worked just fine for them. I am also suspecting that the filename variable could be causing problems because it is a character array on the stack that is dynamically allocated, only in certain cases?