-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
84 lines (67 loc) · 1.67 KB
/
shell.c
File metadata and controls
84 lines (67 loc) · 1.67 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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int is_executable(const char *path) {return access(path, X_OK) == 0;}
char *find_in_path(const char *command) {
char *path_env = getenv("PATH");
if(path_env == NULL){
return NULL;
}
char *path_copy = strdup(path_env);
char *dir = strtok(path_copy, ":");
static char full_path[1024];
while (dir != NULL) {
snprintf(full_path, sizeof(full_path), "%s/%s",dir,command);
if(is_executable(full_path)){
free(path_copy);
return full_path;
}
dir = strtok(NULL, ":");
}
free(path_copy);
return NULL;
}
int main(){
char input[100];
while(1){
printf("project_shell$ ");
fflush(stdout);
if (fgets(input,sizeof(input), stdin)== NULL){
break;
}
input[strcspn(input,"\n")] = 0;
if (strlen(input) == 0){
continue;
}
if(strcmp(input, "exit 0") == 0){
return 0;
}
if(strncmp(input,"echo ", 5) == 0){
printf("%s\n", input + 5);
continue;
}
if(strcmp(input,"pwd") == 0){
char cwd[1024];
getcwd(cwd, sizeof(cwd));
printf("%s\n", cwd);
continue;
}
if(strncmp(input, "type ", 5) == 0) {
char *command = input + 5;
if (strcmp(command,"echo") == 0 || strcmp(command, "exit") == 0 || strcmp(command, "type") == 0) {
printf("%s is a shell builtin\n", command);
}else {
char *path = find_in_path(command);
if(path){
printf("%s is %s \n", command, path);
}else {
printf("%s: not found \n", command);
}
}
continue;
}
printf("%s: command not found\n", input);
}
return 0;
}