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/09/09 13:39:13 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
33/*
34 int redirect_out(t_ast *node, t_ms_data *data)
35 {
36 pid_t pid;
37 int status;
38 int fd;
39
40 pid = fork();
41 if (pid == -1)
42 return (1);
43 if (pid == 0)
44 {
45 if (data->std_out == -1)
46 {
47 data->std_out = open_file(node->right, ">");
48 if (data->std_out == -1)
49 return (1);
50 }
51 else
52 {
53 fd = open_file(node->right, ">");
54 if (fd == -1)
55 return (1);
56 dup2(fd, STDOUT_FILENO);
57 close(fd);
58 }
59 execute_ast(node->left, data);
60 exit(0);
61 }
62 waitpid(pid, &status, 0);
63 return (WEXITSTATUS(status));
64 }
65 */
66
67static int open_and_redirect(t_ast *node, t_ms_data *data)
68{
69 int fd;
70
71 if (data->std_out == -1)
72 {
73 data->std_out = open_file(node->right, ">");
74 if (data->std_out == -1)
75 return (1);
76 }
77 else
78 {
79 fd = open_file(node->right, ">");
80 if (fd == -1)
81 return (1);
82 dup2(fd, STDOUT_FILENO);
83 close(fd);
84 }
85 return (0);
86}
87
88int redirect_out(t_ast *node, t_ms_data *data)
89{
90 pid_t pid;
91 int status;
92
93 pid = fork();
94 if (pid == -1)
95 return (1);
96 if (pid == 0)
97 {
98 if (open_and_redirect(node, data) != 0)
99 exit(1);
100 execute_ast(node->left, data);
101 exit(0);
102 }
103 waitpid(pid, &status, 0);
104 return (WEXITSTATUS(status));
105}
int execute_ast(t_ast *node, t_ms_data *data)
execute Abstract Syntax Tree
Definition execute.c:38
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