Browse Source

[norm] move pipe function.

Moul 4 years ago
parent
commit
5e7fd396f1
3 changed files with 25 additions and 27 deletions
  1. 22 26
      src/pipe.c
  2. 1 1
      src/sh.h
  3. 2 0
      tests.sh

+ 22 - 26
src/pipe.c

@@ -28,46 +28,42 @@ void	launch_pipe(char *all_cmd)
 		cmd_pipe[i] = ft_strtrim(cmd_pipe[i]);
 		if (check_cmd_presence(cmd_pipe[i]) != 1)
 		{
-			error_message("", "no command between pipes", NULL);
+			error_message("", "no command between pipes or semicolons", NULL);
 			return ;
 		}
 		cmd_opt[i] = cmd_split(cmd_pipe[i], ' ', '\t');
 	}
 	cmd_opt[i] = NULL;
-	handle_multi_piping(fd, pipe_nbr, cmd_opt);
+	i = -1;
+	while (++i <= pipe_nbr)
+		handle_multi_piping(fd, pipe_nbr, cmd_opt, i);
+	i = -1;
+	while (++i <= pipe_nbr)
+		wait(NULL);
 }
 
-void	handle_multi_piping(int **fd, int pipe_nbr, char ***cmd_opt)
+void	handle_multi_piping(int **fd, int pipe_nbr, char ***cmd_opt, int i)
 {
-	int		i;
-
-	i = -1;
-	while (++i <= pipe_nbr)
+	if (ft_strcmp(cmd_opt[i][0], "exit") == 0)
+		exit(0);
+	if (fork() == 0)
 	{
-		if (ft_strcmp(cmd_opt[i][0], "exit") == 0)
-			exit(0);
-		if (fork() == 0)
+		if (i < pipe_nbr)
 		{
-			if (i < pipe_nbr)
-			{
-				close(fd[i][0]);
-				dup2(fd[i][1], STDOUT);
-			}
-			if (i > 0)
-			{
-				close(fd[i - 1][1]);
-				dup2(fd[i - 1][0], STDIN);
-			}
-			manage_cmd(cmd_opt[i]);
-			exit(0);
+			close(fd[i][0]);
+			dup2(fd[i][1], STDOUT);
 		}
 		if (i > 0)
 		{
-			close(fd[i - 1][0]);
 			close(fd[i - 1][1]);
+			dup2(fd[i - 1][0], STDIN);
 		}
+		manage_cmd(cmd_opt[i]);
+		exit(0);
+	}
+	if (i > 0)
+	{
+		close(fd[i - 1][0]);
+		close(fd[i - 1][1]);
 	}
-	i = -1;
-	while (++i <= pipe_nbr)
-		wait(NULL);
 }

+ 1 - 1
src/sh.h

@@ -27,7 +27,7 @@ void	split_cmd_and_his_options(char *cmd);
 ** pipe.c
 */
 void	launch_pipe(char *all_cmd);
-void	handle_multi_piping(int **fd, int pipe_nbr, char ***cmd_opt);
+void	handle_multi_piping(int **fd, int pipe_nbr, char ***cmd_opt, int i);
 /*
 ** cmd_split.c
 */

+ 2 - 0
tests.sh

@@ -54,6 +54,8 @@ tests=(
 "ls | cat | wc -l" # different commands
 "ls | cat | cat | cat | cat | cat | cat | cat | cat | cat | cat \
 	| cat | cat | cat | cat | cat | cat | cat | cat | cat | cat" # twenty pipes
+"ls || cat" # Segfault
+"ls ||||||||| cat"
 
 ## Redirections droite
 #"ls > /tmp/toto ; cat /tmp/toto" # simple