-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2son.c
79 lines (70 loc) · 2.72 KB
/
2son.c
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
76
77
78
79
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* 2son.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guilmira <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/19 11:03:47 by guilmira #+# #+# */
/* Updated: 2021/12/06 10:59:47 by guilmira ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
/** PURPOSE : Recieves input from file if needed. */
static void input_form_file(char *path)
{
int fd_file;
fd_file = open(path, O_RDONLY);
if (fd_file < 0)
ft_shut(FILE_ERROR, 1);
if (dup2(fd_file, STDIN_FILENO) == -1)
ft_shut(DUP_ERROR, 0);
close(fd_file);
}
/** PURPOSE : Sends output to file if needed. */
static void output_to_file(char *path)
{
int fd_file;
fd_file = open(path, O_WRONLY | O_CREAT, FULL_PERMISSIONS);
if (fd_file < 0)
ft_shut(FILE_ERROR, 1);
if (dup2(fd_file, STDOUT_FILENO) == -1)
ft_shut(DUP_ERROR, 0);
close(fd_file);
}
/** PURPOSE : Executes first forked proccess. The only thing
* that it takes into account is if input comes from file. */
void first_son(t_arguments *args)
{
int fd_write;
t_command *command_struct;
command_struct = NULL;
command_struct = ft_lst_position(args->commands_lst, args->command_number);
if (!command_struct)
ft_shutdown(LST, 0, args);
fd_write = prepare_process(args->fds[0], args->fds[1]);
if (args->flag_file)
input_form_file(args->file_input);
if (dup2(fd_write, STDOUT_FILENO) == -1)
ft_shutdown(DUP_ERROR, 0, args);
close(fd_write);
if (execve(command_struct->path, command_struct->command, NULL) == -1)
ft_shutdown(EXE_ERROR, 0, args);
}
/** PURPOSE : Executes first forked proccess. The only thing
* that it takes into account is if output comes from file. */
void last_son(int index, t_arguments *args)
{
t_command *command_struct;
command_struct = NULL;
command_struct = ft_lst_position(args->commands_lst, args->command_number);
if (!command_struct)
ft_shutdown(LST, 0, args);
if (dup2(args->fds[index], STDIN_FILENO) == -1)
ft_shutdown(DUP_ERROR, 0, args);
close(args->fds[index]);
if (args->flag_file)
output_to_file(args->file_output);
if (execve(command_struct->path, command_struct->command, NULL) == -1)
ft_shutdown(EXE_ERROR, 0, args);
}