Here is my pipe to pipe function:
int *pip
is the pipe that I want to read fromchar **cmd
is the command that I want to executechar **envp
points to the environment variablesI want to take the pipe (pip) as STDIN with dup2 and take the new pipe (fd) as STDOUT also with dup2
The problem is that when it comes to execve the command is executed but the program is stuck in an infinite loop
int *pipe_to_pipe(int *pip, char **cmd, char **envp) {
int *fd;
int pid;
fd = (int *)malloc(sizeof(int) * 2);
if (!fd || pipe(fd) == -1)
error(1);
pid = fork();
if (pid == -1)
error(1);
if (pid == 0)
{
dup2(pip[0], STDIN_FILENO);
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(pip[1]);
execve((command_path), cmd, envp);
exit(0);
}
wait(NULL);
free(pip);
return (fd);
}
As an example, if I have "hello world" in my int *pip
as a char **cmd I have cmd[0] = "cat", cmd[1] = "-e".
When I make execve(path, cmd, envp);
the program cat "hello world" and infinite loop here.
How can I fix this?
The problem comes from the fact that I didn't close the pipe "pip" in the parent process adding those lines that would be executed by the parent process fix everything
if (pid != 0){
close(pip[0]);
close(pip[1]);
wait(NULL);
}
Otherwise it fixes my problem I don't understand why if someone can explain to me I will be gratefull Thanks to everyone that answered me <3