-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.c
More file actions
49 lines (42 loc) · 1.16 KB
/
executor.c
File metadata and controls
49 lines (42 loc) · 1.16 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
#include "executor.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
int execute(char **args, Redirect *redir) {
pid_t pid = fork();
if (pid == 0) {
if (redir->outfile != NULL) {
int flags = O_WRONLY | O_CREAT;
flags |= redir->append ? O_APPEND : O_TRUNC;
int fd = open(redir->outfile, flags, 0644);
if (fd < 0) {
perror("mysh: open");
exit(1);
}
dup2(fd, STDOUT_FILENO);
close(fd);
}
if (redir->infile != NULL) {
int fd = open(redir->infile, O_RDONLY);
if (fd < 0) {
perror("mysh: open");
exit(1);
}
dup2(fd, STDIN_FILENO);
close(fd);
}
execvp(args[0], args);
fprintf(stderr, "mysh: %s: command not found\n", args[0]);
exit(127);
} else if (pid > 0) {
int status;
waitpid(pid, &status, 0);
return WEXITSTATUS(status);
} else {
perror("mysh: fork");
return -1;
}
}