1

I have this following recursive and forking function that takes in an array of a command line input that has already been split by strsep (based on spaces between words) and with no redirections (eg something like ls | wc). However, when the code takes in a command line input that involves more than two pipes, the command after the second pipe is unable get the output from the command before the second pipe. Is there a way to fix this issue?

int *pipefd;
int pipeNum;
int pipes;
int status;

void executeCommandFork(char **commands, int start, int end, int loopNum)
{
    char **args;
    int i;
    int forked = fork();
    for (; end < lengthOfArray(commands) && *commands[end] != '|'; end++)
        ;
    int newStart = end + 1;
    end--;
    args = malloc(end - start + 2);
    args[end - start + 1] = NULL;
    for (; end >= start; end--)
    {
        args[end - start] = commands[end];
    }
    if (forked == 0)
    {
        if (pipeNum - 2 >= 0)
        {
            dup2(pipefd[pipeNum - 2], STDIN_FILENO);
        }

        if (pipeNum + 1 < pipes * 2)
        {
            dup2(pipefd[pipeNum + 1], STDOUT_FILENO);
        }

        closePipes();

        execvp(args[0], args);
        free(args);
    }
    else
    {
        pipeNum += 2;
        if (pipeNum <= pipes * 2)
        {
            executeCommandFork(commands, newStart, newStart, loopNum + 1);
        }
    }

}

void executeCommand(char **commands, int pipes) //this will deal with pipings
{
    pipefd = malloc(sizeof(int) * pipes);
    int i;
    for (i = 0; i < pipes; i++)
    {
        pipe(pipefd + i * 2);
    }

    executeCommandFork(commands, 0, 0, 0);
    closePipes();

    pipeNum = 0;
}
Andy Lin
  • 11
  • 1
  • 3
  • Please see my comments in this recent question https://stackoverflow.com/questions/70145745/will-processes-be-blocked-if-the-number-of-child-processes-greater-than-process and the link therein to a working solution from an old answer of mine – Craig Estey Nov 29 '21 at 01:57
  • Thanks. Turns out file table values were getting jumbled up in my recursive part and mallocing to a pointer was the fix. – Andy Lin Nov 29 '21 at 15:33

1 Answers1

0

Turns out, pipefd = malloc(sizeof(int) * pipes); was a faulty line. Using an int pointer did the trick.

Andy Lin
  • 11
  • 1
  • 3