I'm actually working on project and we're trying to recreate a bash terminal in C. I've got some problems about handling pipes in my code. As you know when you write "cat | ls", it first shows ls result then standard input is opened but only for one line. The problem is the way I'm handling pipes, in first it shows the ls result as excepted but after the standard input is reading until I make CTRL-D. I want to make it end after the first line, like bash does. I think I have a problem with my pipes but I tried to remake things in other ways and it's always the same problem.
My code :
void make_command(t_list *cmds, char **env)
{
char *path;
int exec;
path = get_path((char *)cmds->content[0], env);
if (!path)
return ;
exec = execve(path, (char **)cmds->content, env);
if (exec < 0)
exit_error();
}
void make_pipe(t_list *cmds, char **env, t_listpids **pids, int *fd_old)
{
pid_t pid;
int tube[2];
while (cmds)
{
if (pipe(tube) == -1)
exit_error();
pid = fork();
if (pid == 0)
{
if (cmds->previous) //only if not first command
{
dup2((*fd_old), STDIN_FILENO);
close(*fd_old);
}
if (cmds->next) //only if not last command
{
dup2(tube[1], STDOUT_FILENO);
close(tube[1]);
}
make_command(cmds, env); //execute command function with execve
close(tube[0]);
close(tube[1]);
exit(EXIT_SUCCESS);
}
else
{
add_pids(pid, pids); //add pid to chained list of pids (used to waitpid them after)
*fd_old = tube[0];
close(tube[1]);
cmds = cmds->next;
while (cmds && ft_strncmp((char *)cmds->content[0], "|", 1) == 0)
cmds = cmds->next;
}
}
}