-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
151 lines (129 loc) · 2.19 KB
/
Copy pathshell.c
File metadata and controls
151 lines (129 loc) · 2.19 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define TOK_DELIM " \t\r\n"
#define RED "\033[0;31m"
#define RESET "\e[0m"
#define TK_BUFF_SIZE 1024
char *read_line();
char **split_line(char *);
int dash_exit(char **);
int dash_execute(char **);
char *read_line()
{
int buffsize = 1024;
int position = 0;
char * buffer = malloc(sizeof(char) * buffsize);
int c;
if(!buffer)
{
fprintf(stderr, "%sdash: Allocation error%s\n", RED, RESET);
exit(EXIT_FAILURE);
}
while(1)
{
c = getchar();
if( c == EOF || c == '\n')
{
buffer[position] = '\0';
return buffer;
}
else
{
buffer[position] = c;
}
position++;
if(position >= buffsize)
{
buffsize += 1024;
buffer = realloc(buffer, buffsize);
if(!buffer)
{
fprintf(stderr, "dash: Allocation error\n");
exit(EXIT_FAILURE);
}
}
}
}
char **split_line(char * line)
{
int buffsize = 1024, position = 0;
char * * tokens = malloc(buffsize * sizeof(char *));
char * token;
if(!tokens)
{
fprintf(stderr, "%sdash: Allocation error%s\n", RED, RESET);
exit(EXIT_FAILURE);
}
token = strtok(line, TOK_DELIM);
while(token != NULL)
{
tokens[position] = token;
position++;
if(position >= buffsize)
{
buffsize += TK_BUFF_SIZE;
tokens = realloc(tokens, buffsize * sizeof(char *));
if(!tokens)
{
fprintf(stderr, "%sdash: Allocation error%s\n", RED, RESET);
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
}
int dash_exit(char **args)
{
return 0;
}
int dash_execute(char **args)
{
pid_t cpid;
int status;
if(strcmp(args[0], "exit") == 0)
{
return dash_exit(args);
}
cpid = fork();
if(cpid == 0)
{
if(execvp(args[0], args) < 0)
{
printf("dash: command not found: %s\n", args[0]);
}
exit(EXIT_FAILURE);
}
else if(cpid < 0)
{
printf(RED "Error forking"
RESET "\n");
}
else
{
waitpid(cpid, & status, WUNTRACED);
}
return 1;
}
void loop()
{
char * line;
char * * args;
int status = 1;
do
{
printf("> ");
line = read_line();
args = split_line(line);
status = dash_execute(args);
free(line);
free(args);
} while (status);
}
int main() {
loop();
return 0;
}