-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuiltins.c
137 lines (126 loc) · 2.78 KB
/
builtins.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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <signal.h>
#include "builtins.h"
#include "config.h"
int echo(char*[]);
int lexit(char*[]);
int lcd(char*[]);
int lls(char*[]);
int lkill(char*[]);
int undefined(char*[]);
builtin_pair builtins_table[]={
{"exit", &lexit},
{"lecho", &echo},
{"lcd", &lcd},
{"lkill", &lkill},
{"lls", &lls},
{NULL,NULL}
};
void reportError(char *arr) {
fprintf(stderr, "Builtin %s error.\n", arr);
}
int echo(char * argv[])
{
int i =1;
if (argv[i]) printf("%s", argv[i++]);
while (argv[i])
printf(" %s", argv[i++]);
printf("\n");
fflush(stdout);
return 0;
}
int lexit(char *argv[]) {
char* test;
int x;
if(argv[2]) {
reportError("exit");
return BUILTIN_ERROR;
}
if(argv[1]) {
x = strtol(argv[1], &test, 10);
if(*test != '\0') {
reportError("exit");
return BUILTIN_ERROR;
}
exit(x);
}
exit(0);
}
int lkill(char *argv[]) {
if (!argv[1] || argv[3]) {
reportError("lkill");
return BUILTIN_ERROR;
}
int x, y;
char* test, *ttest;
if (!argv[2]) {
x = strtol(argv[1], &test, 10);
if (*test != '\0') {
reportError("lkill");
return BUILTIN_ERROR;
}
return kill(x, SIGTERM);
}
x = strtol(argv[1] + 1, &test, 10);
y = strtol(argv[2], &ttest, 10);
if (*test != '\0' || *ttest != '\0') {
reportError("lkill");
return BUILTIN_ERROR;
}
return kill(y, x);
}
int lls(char* argv[]) {
if(!argv[1]) {
DIR *dir = opendir(".");
struct dirent *file;
while ((file = readdir(dir)) != NULL)
if(file -> d_name[0] != '.')
printf("%s\n", file -> d_name);
fflush(stdout);
if (dir != NULL)
closedir(dir);
return 0;
}
else {
reportError("lls");
return BUILTIN_ERROR;
}
}
int lcd(char * argv[]) {
if(argv[2]) {
reportError("lcd");
return BUILTIN_ERROR;
}
char cwd[BUFFER_SIZE];
if(argv[1]) {
if(argv[1][0] != '/') {
getcwd(cwd, sizeof(cwd));
strcat(cwd, "/");
strcat(cwd, argv[1]);
if(chdir(cwd) == -1) {
fprintf(stderr, "%s\n", cwd);
reportError("lcd");
return BUILTIN_ERROR;
}
}
else if(chdir(argv[1]) == -1) {
reportError("lcd");
return BUILTIN_ERROR;
}
}
else if(chdir(getenv("HOME")) == -1) {
reportError("lcd");
return BUILTIN_ERROR;
}
return 0;
}
int
undefined(char * argv[])
{
fprintf(stderr, "Command %s undefined.\n", argv[0]);
return BUILTIN_ERROR;
}