Repository navigation
Expand file tree
/
Copy pathexecutor.c
More file actions
120 lines (113 loc) · 3.31 KB
/
Copy pathexecutor.c
File metadata and controls
120 lines (113 loc) · 3.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include "executor.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int execute_command(const Command *cmd) {
int file_fd = -1;
if (cmd->right_argv != NULL) {
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe");
return -1;
}
pid_t left_pid = fork();
if (left_pid == -1) {
perror("fork");
close(pipefd[0]);
close(pipefd[1]);
return -1;
}
if (left_pid == 0) {
if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
perror("dup2");
close(pipefd[0]);
close(pipefd[1]);
_exit(1);
}
close(pipefd[0]);
close(pipefd[1]);
execvp(cmd->argv[0], cmd->argv);
if (errno == ENOENT) {
fprintf(stderr, "shall: command not found: %s\n", cmd->argv[0]);
} else {
perror(cmd->argv[0]);
}
_exit(127);
}
pid_t right_pid = fork();
if (right_pid == -1) {
perror("fork");
close(pipefd[0]);
close(pipefd[1]);
waitpid(left_pid, NULL, 0);
return -1;
}
if (right_pid == 0) {
if (dup2(pipefd[0], STDIN_FILENO) == -1) {
perror("dup2");
close(pipefd[0]);
close(pipefd[1]);
_exit(1);
}
close(pipefd[0]);
close(pipefd[1]);
execvp(cmd->right_argv[0], cmd->right_argv);
if (errno == ENOENT) {
fprintf(stderr, "shall: command not found: %s\n", cmd->right_argv[0]);
} else {
perror(cmd->argv[0]);
}
_exit(127);
}
close(pipefd[0]);
close(pipefd[1]);
waitpid(left_pid, NULL, 0);
waitpid(right_pid, NULL, 0);
return 1;
}
pid_t pid = fork();
if (pid > 0) {
waitpid(pid, NULL, 0);
} else if (pid == 0) {
if (cmd->output_file != NULL) {
file_fd = cmd->append_mode ? open(cmd->output_file, O_WRONLY | O_CREAT | O_APPEND, 0644)
: open(cmd->output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (file_fd == -1) {
perror(cmd->output_file);
_exit(1);
}
if (dup2(file_fd, STDOUT_FILENO) == -1) {
perror("dup2");
close(file_fd);
_exit(1);
}
close(file_fd);
}
if (cmd->input_file != NULL) {
file_fd = open(cmd->input_file, O_RDONLY);
if (file_fd == -1) {
perror(cmd->input_file);
_exit(1);
}
if (dup2(file_fd, STDIN_FILENO) == -1) {
perror("dup2");
close(file_fd);
_exit(1);
}
close(file_fd);
}
execvp(cmd->argv[0], cmd->argv);
if (errno == ENOENT) {
fprintf(stderr, "shall: command not found: %s\n", cmd->argv[0]);
} else {
perror(cmd->argv[0]);
}
_exit(1);
} else {
perror("fork");
return -1;
}
return 1;
}