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;
}