connec_pipe_cmd_execute: setup pipes between commands

This commit is contained in:
Khaïs COLIN 2025-04-08 16:18:57 +02:00
parent 81febcfcdd
commit 871180f6d8
Signed by: logistic-bot
SSH key fingerprint: SHA256:RlpiqKeXpcPFZZ4y9Ou4xi2M8OhRJovIwDlbCaMsuAo
4 changed files with 96 additions and 23 deletions

View file

@ -0,0 +1,72 @@
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* connec_pipe_cmd_execute.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: khais <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/04/11 12:01:29 by khais #+# #+# */
/* Updated: 2025/04/11 12:02:26 by khais ### ########.fr */
/* */
/* ************************************************************************** */
#include "connec_pipe_cmd_execute.h"
#include "../common/do_waitpid.h"
#include <unistd.h>
#include <stdio.h>
#include "../cmd/cmd_execute.h"
static void pipe_do_close(int pipefd[2])
{
close(pipefd[0]);
close(pipefd[1]);
}
static void dup_and_close(int fd, int fd2, int pipefd[2])
{
dup2(fd, fd2);
pipe_do_close(pipefd);
}
static int do_pipe(int pipefd[2], t_minishell *app)
{
if (pipe(pipefd) < 0)
{
perror("minishell: pipe");
app->last_return_value = 2;
return (-1);
}
return (0);
}
static void close_and_wait(t_minishell *app, int pid1, int pid2, int pipefd[2])
{
pipe_do_close(pipefd);
do_waitpid(app, pid1);
do_waitpid(app, pid2);
}
void connec_pipe_cmd_execute(t_connec_cmd *cmd, t_minishell *app)
{
int pid1;
int pid2;
int pipefd[2];
if (do_pipe(pipefd, app) < 0)
return ;
pid1 = fork();
if (pid1 == 0)
{
dup_and_close(pipefd[1], STDOUT_FILENO, pipefd);
cmd_execute(cmd->first, app);
return ;
}
pid2 = fork();
if (pid2 == 0)
{
dup_and_close(pipefd[0], STDIN_FILENO, pipefd);
cmd_execute(cmd->second, app);
}
else
close_and_wait(app, pid1, pid2, pipefd);
}