-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredir.c
More file actions
75 lines (69 loc) · 2.31 KB
/
Copy pathredir.c
File metadata and controls
75 lines (69 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* redir.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yucchen <yucchen@student.42singapore.sg +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/12/02 16:25:28 by yucchen #+# #+# */
/* Updated: 2026/01/09 14:57:10 by yucchen ### ########.fr */
/* */
/* ************************************************************************** */
#include "executor.h"
static void unlink_file(t_redir *redir)
{
if (redir->is_heredoc_tmp)
unlink(redir->file);
}
int apply_redirs(t_cmd *cmd)
{
int fd;
t_redir *redir;
redir = cmd->redirs;
while (redir)
{
if (redir->type == R_IN)
fd = open(redir->file, O_RDONLY);
else if (redir->type == R_OUT)
fd = open(redir->file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
else if (redir->type == R_APPEND)
fd = open(redir->file, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd == -1)
return (unlink_file(redir), perror(redir->file), 1);
if (redir->type == R_IN && dup2(fd, STDIN_FILENO) == -1)
return (unlink_file(redir), perror("dup2"), close(fd), 1);
if ((redir->type == R_OUT || redir->type == R_APPEND)
&& dup2(fd, STDOUT_FILENO) == -1)
return (perror("dup2"), close(fd), 1);
close(fd);
unlink_file(redir);
redir = redir->next;
}
return (0);
}
int apply_redirs_touch(t_cmd *cmd)
{
int fd;
t_redir *redir;
redir = cmd->redirs;
while (redir)
{
if (redir->type == R_IN)
fd = open(redir->file, O_RDONLY);
else if (redir->type == R_OUT)
fd = open(redir->file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
else if (redir->type == R_APPEND)
fd = open(redir->file, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd == -1)
{
if (redir->is_heredoc_tmp)
unlink(redir->file);
return (perror(redir->file), 1);
}
close(fd);
if (redir->is_heredoc_tmp)
unlink(redir->file);
redir = redir->next;
}
return (0);
}