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
|
#ifndef shell_builtins
#define shell_builtins
#include "lsh_main_func.c"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
/*
Function Declarations for builtin shell commands:
*/
int lsh_cd(char **args);
int lsh_help(char **args);
int lsh_exit(char **args);
int export(char **args);
/*
List of builtin commands, followed by their corresponding functions.
*/
char *builtin_str[] = {
"cd",
"help",
"exit",
"export"
};
int (*builtin_func[]) (char **) = {
&lsh_cd,
&lsh_help,
&lsh_exit,
&export
};
int lsh_num_builtins() {
return sizeof(builtin_str) / sizeof(char *);
}
/*
Builtin function implementations.
*/
int lsh_cd(char **args)
{
if (args[1] == NULL) {
fprintf(stderr, "lsh: expected argument to \"cd\"\n");
} else {
int err = chdir(args[1]);
if (err != 0) {
perror("lsh");
}
char *cwd=(char*)malloc(sizeof(char)*4096);
if (!cwd) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
getcwd(cwd,sizeof(char*)*4096);
setenv("PWD",cwd,1);
free(cwd);
}
return 1;
}
int lsh_help(char **args)
{
int i;
printf("FOX SHELL\n");
printf("Type program names and arguments, and hit enter.\n");
printf("The following are built in:\n");
for (i = 0; i < lsh_num_builtins(); i++) {
printf(" %s\n", builtin_str[i]);
}
printf("Use the man command for information on other programs.\n");
return 1;
}
int lsh_exit(char **args)
{
return 0;
}
int export(char **args){
char *token;
int position = 0;
char *key = NULL;
char *value = NULL;
token = strtok(args[1], "=\r\n");
while (token != NULL) {
if(position == 0){
key=token;
} else if(position == 1){
value=token;
}
position++;
token = strtok(NULL, "=\r\n");
}
setenv(key,value,1);
return 1;
}
int lsh_execute(char **args)
{
int i;
if (args[0] == NULL) {
// An empty command was entered.
return 1;
}
for (i = 0; i < lsh_num_builtins(); i++) {
if (strcmp(args[0], builtin_str[i]) == 0) {
return (*builtin_func[i])(args);
}
}
return lsh_launch(args);
}
#endif
|