0

I have a linked list stored with command line arguments such as ls -l (first one doesn't need input) however the 2nd to last commands require input such as grep pattern. In my implementation I remove the command from a linked list (for e.g: {"ls", "-l", NULL}). this is later passed along to the execve() system call. the pathname variable before its concatenated is just "/bin/\0". Anyway, The second to the one before the last processes all read from redirected output and then redirect their output for the next process. Last one just reads (no redirection). code below.

while(!isEmpty(commands))
{
    pathname  = (char*)malloc(20*sizeof(char));
    resetpathname(pathname);
    args =  (char**)removeStart(commands);
    strcat(pathname, args[0]);
    pid = fork();
    if (pid==0) 
    {
        if(i==0)/*first iteration - 1st process requires no input: write*/
        {
            close(fds[0]);
            dup2(fds[1],1);/*write operation*/
        }/*first iteration - 1st process requires no input*/
        else if(i==1 && !isEmpty(commands))
        {
            dup2(fds[0],0);/*read op*/
            dup2(fds[1],1);/*write operation*/   
        }/*2nd iteration to <last>-1th iteration: read and write*/
        else if(isEmpty(commands))
        {
            close(fds[1]);
            dup2(fds[0],0);/*read op*/
        }/*last iteration: read*/
        execve(pathname, args, envp);
    }
    else if (pid>0)
    {
        if(i==0)
        {
            close(fds[1]);
        }
        if(i==1 && !isEmpty(commands))
        {
            close(fds[0]);
            close(fds[1]);
        }
        else if(isEmpty(commands))
        {
            close(fds[0]);
        }/
        wait (NULL);         
    }
    i=1;/*flag for reading redirected output. first process doesn't read*/ 
}

only the first two commands will execute if my linked list is holding: 1: man man 2: grep manual 3: tail

Lezcer
  • 17
  • 1
  • 5
  • 1
    Search in the search box above `"[c] pipe fork dup2 corpse"` (without the quotes) and you will hit gold. [Trying to implement piping in C - shell is hanging and not running commands](https://stackoverflow.com/a/54602339/3422102) is probably as good as any to start with. – David C. Rankin May 23 '21 at 07:50
  • @DavidC.Rankin thank you – Lezcer May 23 '21 at 08:04
  • The `"corpse"` word ties the answers to one particular (very skilled) contributor on this site `:)` – David C. Rankin May 23 '21 at 08:06

0 Answers0