wiwi
wiwi

Reputation: 1

While making Custom Shell in Operating System, why did dup2() call terminated the child process before even calling the execvp()?

`I am trying to make custom shell in Operating System, only based on Pipes, I/O direction and basic commands that are executed by execvp() command. But I am having difficulties in my code while using the dup2() command. Using multiple file descriptors is causing a lot of confusion. Here's the snippet of my code :

int f2[2];
pipe(f2);
          
int retval2 = fork();
if(retval2 ==  0)
{
    printf("IF statement\n");
    if(input_direct !=  STDIN_FILENO)
    {
         dup2(input_direct, STDIN_FILENO);
         close(input_direct);
     }
    printf("statement before calling Dup2(f2[1])\n");
    dup2(f2[1] , STDOUT_FILENO);
    close(f2[0]);
    close(f2[1]);
               
    printf("statement before calling RSC()\n");
    RunSubCommand(token, startindex, endindex);
               
}
else if(retval2 > 0)
{                  
   close(f2[1]);
   wait(NULL);
   input_direct = f2[0];  
          
          
}
void RunSubCommand(char ** token, int startindex, int endindex)
{
     printf("RunSubCommand Fucntion Call: \n");
     char * args[(endindex - startindex)+1];
     int i=0,j=0, end, start;
     start = startindex;
     end = endindex - startindex;
     while(i < end)
     {
          args[i] = token[start];
          i++;
          start++;
      }
     args[i] = NULL;
     printf("Printing args: \n");
     for(j=0;j<i;j++)
     {
          printf("%s\n", args[i]);

     }
     execvp(args[0], args);
     perror("Error in executing EXECVP\n");
 
}

when I enter a command such as: sort input.txt, the child process terminates after dup2(f2[1] , STDOUT_FILENO); and the RunSubCommand() function remains un-used. Moreover, I also removed the RunSubCommand() call and tried adding the functionality of RunSubCommand in the above code but the result is still the same. I know there is a problem with the file descriptors but I can not get my head around it. Can anyone please suggest a feasible solution? You have no clue how much I need help right now. `

Upvotes: 0

Views: 22

Answers (0)

Related Questions