I'm attempting to create a recursive piping function using dup2()
, fork()
, and pipe()
. However, when my array is something like {"ls", "grep shell"}
(where shell is the name of my shell), it goes in an endless loop of displaying the results of ls and saying "write error: bad file descriptor". I'm sure that somehow I'm not properly terminating my recursion, and I suspect the issue is with trying to dup either fd[1]
or fd[0]
, but after debugging this for hours I still can't figure it out. Any help is appreciated!
void recursive_piping(char *recursive_pipe_args[MAX_ARGS]) {
int i = 0;
int fd[2];
char *first_arg[2] = {"", NULL};
char *rest_of_args[81];
// if its of size 1, base case
if (recursive_pipe_args[1] == NULL) {
if (execvp(recursive_pipe_args[0], recursive_pipe_args) == -1) {
printf("\nExecute didn't work");
fflush(stdout);
}
return;
}
// recursive case, split args into the first on and the rest of them
first_arg[0] = recursive_pipe_args[0];
for (i = 0; i < (num_pipes); i++) {
rest_of_args[i] = malloc(81);
strcpy(rest_of_args[i], recursive_pipe_args[i+1]);
}
if (pipe(fd) < 0) {
printf("\npipe Failure");
}
// parent section, reads file descriptor fd[0]
if (fork()) {
close(fd[0]);
dup2(fd[1], 0);
recursive_piping(rest_of_args);
// return;
}
close(fd[1]);
dup2(fd[0], 1);
execvp(first_arg[0], first_arg);
}