-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.c
More file actions
74 lines (64 loc) · 1.62 KB
/
Copy pathexecutor.c
File metadata and controls
74 lines (64 loc) · 1.62 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include "parser.h"
void run_command(char **args) {
for (int i = 0; args[i]; i++) {
if (strcmp(args[i], ">") == 0 && args[i+1]) {
int fd = open(args[i+1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
dup2(fd, STDOUT_FILENO);
close(fd);
args[i] = NULL;
} else if (strcmp(args[i], "<") == 0 && args[i+1]) {
int fd = open(args[i+1], O_RDONLY);
dup2(fd, STDIN_FILENO);
close(fd);
args[i] = NULL;
}
}
execvp(args[0], args);
perror("exec");
exit(1);
}
void handle_pipe(char *input) {
char *left = strtok(input, "|");
char *right = strtok(NULL, "|");
if (!right) return;
int pipefd[2];
pipe(pipefd);
pid_t p1 = fork();
if (p1 == 0) {
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[0]); close(pipefd[1]);
char *args[64];
parse_input(left, args);
run_command(args);
}
pid_t p2 = fork();
if (p2 == 0) {
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[1]); close(pipefd[0]);
char *args[64];
parse_input(right, args);
run_command(args);
}
close(pipefd[0]); close(pipefd[1]);
wait(NULL); wait(NULL);
}
void execute_input(char *input) {
if (strchr(input, '|')) {
handle_pipe(input);
return;
}
pid_t pid = fork();
if (pid == 0) {
char *args[64];
parse_input(input, args);
run_command(args);
} else {
wait(NULL);
}
}