-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
122 lines (104 loc) · 2.64 KB
/
Copy pathshell.c
File metadata and controls
122 lines (104 loc) · 2.64 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.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 **);
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;
}
int dash_exit(char **args){
return 0;
}
char **split_line(char *line){
int buffsize=TK_BUFF_SIZE,position=0;
char **tokens=(char **)malloc(sizeof(char*)*buffsize);
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;
}
char *read_line(){
int buffsize=1024;
int position=0;
char *buffer=(char*)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*sizeof(char));
if(!buffer){
fprintf(stderr,"%sdash: Allocation error%s\n",RED,RESET);
exit(EXIT_FAILURE);
}
}
}
}
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;
}