i am trying to implement a simple bash shell in C, which has to handle pipes and subshells. The main problem is that once I run the command in the subshell, how can I pass the output to the parent process to use the pipe?
the idea behind my program is that when it sees a parenthesis it calls the start function, which calls the function that executes pipes and execve and when it's done the parent picks up where it left off
for the pipe code i followed Implementation of multiple pipes in C, but now i don't know how to share information between two file descriptors.
EDIT:
code of pipe function
void open_pipe(int pipes[], int no_pipes)
{
int i;
i = -1;
while (++i < no_pipes)
pipe(pipes + i * 2);
}
void close_pipe(int pipes[], int no_pipes)
{
int j;
j = 0;
while (j < 2 * no_pipes)
close(pipes[j++]);
}
void ft_exec_pipe(t_shell *shell, int nb_pipe)
{
int i;
int j;
int pipes[2 * nb_pipe];
int status;
pid_t pid;
i = 0;
j = nb_pipe + 1;
open_pipe(pipes, nb_pipe);
while (*(shell->token) && j-- > 0)
{
pid = fork();
if (pid == 0)
{
if (*(shell->token + 1) != NULL)
dup2(pipes[i + 1], STDOUT_FILENO);
if (i != 0)
dup2(pipes[i - 2], STDIN_FILENO);
close_pipe(pipes, nb_pipe);
if (ft_is_subshell(sstoken))
{
shell->fd = pipes[i + 1];
ft_subshell(shell, sstoken);
}
else
ft_exec_cmd_fork(shell);
}
i += 2;
shell->token++;
if (j)
{
shell->last_operator = *(shell->operator);
shell->operator++;
}
}
close_pipe(pipes, nb_pipe);
while (i-- > 0)
waitpid(pid, &status, 0);
shell->exitstatus = WEXITSTATUS(status);
shell->prev_exitstatus = shell->exitstatus;
}
the problem with this code is in reading from the file descriptor after pipe()
, when the program executes commands in the subshell and the parent process filters the output with: wc, grep, head ... loop as if there are problems with input, instead with commands like ls, ps, echo ... work fine. I'm sure I don't handle the input well but I don't know how to fix.