forked from kevinvkell/distributed_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
117 lines (96 loc) · 1.75 KB
/
shell.c
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
//Kevin Kell
//Distributed Systems Project2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <errno.h>
#include "shell.h"
int shell(char *input) {
char *parsed_input[count_arguments(input) + 1];
parse_arguments(input, parsed_input);
if(strcmp("exit", *parsed_input) == 0) {
wait_for_all_children();
exit(0);
}
if(strcmp("cd", *parsed_input) == 0) {
cd(*(parsed_input + 1));
}
int pid = fork();
if(pid < 0) {
perror("fork");
exit(1);
}
if(pid > 0) {
wait(NULL);
}
else {
if(execvp(*parsed_input, parsed_input) == -1) {
perror("execv");
exit(1);
}
}
return 0;
}
int count_arguments(char *input) {
int count = 0;
char *current;
current= input;
while(*current == ' ') {
current++;
}
while(*current != '\0') {
if(*current == ' ') {
current++;
}
else {
count++;
current++;
while(*current != ' ' && *current != '\0') {
current++;
}
}
}
return count;
}
void parse_arguments(char *input, char **parsed_input) {
char **current;
char *saveptr;
char *token;
current = parsed_input;
token = strtok_r(input, "\n ", &saveptr);
if(strlen(token) > 0) {
*current = token;
current++;
}
while((token = strtok_r(NULL, " \n", &saveptr)) != NULL) {
if(strlen(token) > 0) {
*current = token;
current++;
}
}
*current = NULL;
}
void wait_for_all_children() {
int pid;
while((pid = wait(NULL))) {
if(errno == ECHILD) {
break;
}
}
}
void cd(char *path) {
char *new_path = path;
char buffer[strlen(path) + strlen(getenv("HOME")) + 1];
if(*new_path == '~') {
strcpy(buffer, getenv("HOME"));
strcat(buffer, (path + 1));
new_path = buffer;
}
if(chdir(new_path) != 0) {
perror("chdir");
wait_for_all_children();
exit(1);
}
}