-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdavidshell.c
More file actions
93 lines (84 loc) · 1.58 KB
/
davidshell.c
File metadata and controls
93 lines (84 loc) · 1.58 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
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "commands.h"
void shellprint();
char* readline();
char** splitcommand(char* command);
int main(int argc, char** argv){
int exit = 0;
while(!exit){
shellprint();
char* command = readline();
if(strlen(command)){
char** split = splitcommand(command);
exit = execute(split);
}
}
//TODO: cleanup
return 0;
}
void shellprint(){
struct passwd* pw = getpwuid(geteuid());
char* wd = getcwd(NULL,0);
char host[255];
gethostname(host,255);
if(!strncmp(wd,pw->pw_dir,strlen(pw->pw_dir))){
wd += strlen(pw->pw_dir)-1;
*wd = '~';
}
printf("%s:%s:%s$ ",host,pw->pw_name,wd);
}
char* readline(){
size_t length = 80;
char* line = malloc(length);
char c;
int len = 0;
if(!line){
printf("malloc fail");
exit(1);
}
while(1){
c = getchar();
if(c=='\n'||c==EOF){
line[len] = '\0';
return line;
}
line[len] = c;
++len;
if(len%length==0){
line = realloc(line,len+length);
if(line==NULL){
printf("realloc fail");
exit(1);
}
}
}
}
char** splitcommand(char* command){
int cnt = 1;
char* ptr;
char** split;
int i = strlen(command);
for(i=0;i<strlen(command);++i){
if(command[i]==' '){
++cnt;
}
}
split = malloc(cnt*sizeof(char*)+1);
if(split==NULL){
printf("malloc rip");
exit(1);
}
ptr = strtok(command," ");
cnt = 0;
while(ptr!=NULL){
split[cnt]=ptr;
ptr = strtok(NULL," ");
++cnt;
}
split[cnt] = NULL;
return split;
}