maxishell
Implementation of a shell for Linux-like systems
Loading...
Searching...
No Matches
redirect_out.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* redirect_out.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: dmdemirk <dmdemirk@student.42london.c +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/07/11 14:32:59 by dmdemirk #+# #+# */
9/* Updated: 2024/11/07 19:41:36 by dmdemirk ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "tokens.h"
14#include "shell.h"
15#include "redirection.h"
16#include "execute.h"
17#include "pipe.h"
18#include <sys/wait.h>
19
20static int open_and_redirect(t_ast *node, t_ms_data *data);
21int redirect_out(t_ast *node, t_ms_data *data);
22
33static int open_and_redirect(t_ast *node, t_ms_data *data)
34{
35 int fd;
36
37 if (data->std_out == -1)
38 {
39 data->std_out = open_file(node->right, ">");
40 if (data->std_out == -1)
41 return (EXIT_FAILURE);
42 }
43 else
44 {
45 fd = open_file(node->right, ">");
46 if (fd == -1)
47 return (EXIT_FAILURE);
48 dup2(fd, STDOUT_FILENO);
49 close(fd);
50 }
51 return (EXIT_SUCCESS);
52}
53
54int redirect_out(t_ast *node, t_ms_data *data)
55{
56 pid_t pid;
57 int exec_status;
58 int status;
59
60 pid = fork();
61 if (pid == -1)
62 return (EXIT_FAILURE);
63 if (pid == 0)
64 {
65 if (open_and_redirect(node, data) != 0)
66 exit(EXIT_FAILURE);
67 exec_status = execute_ast(node->left, data);
68 exit(exec_status);
69 }
70 if (waitpid(pid, &status, 0) == -1)
71 return (EXIT_FAILURE);
72 if (WIFSIGNALED(status))
73 return (128 + WTERMSIG(status));
74 return (WEXITSTATUS(status));
75}
int execute_ast(t_ast *node, t_ms_data *data)
execute Abstract Syntax Tree
Definition execute.c:38
#define EXIT_SUCCESS
Definition exit_status.h:16
#define EXIT_FAILURE
Definition exit_status.h:17
int redirect_out(t_ast *node, t_ms_data *data)
static int open_and_redirect(t_ast *node, t_ms_data *data)
redirect out ">" to the file output
int open_file(t_ast *node, char *direction)
open file in the context of redirection
Definition utils.c:34
Definition tokens.h:50
struct s_ast * right
Definition tokens.h:54
struct s_ast * left
Definition tokens.h:53
int std_out
Definition shell.h:27