-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
164 lines (140 loc) · 2.04 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
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
152
153
154
155
156
157
158
159
160
161
162
163
164
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<wait.h>
void Cmd(char **a);
void shell();
char **tok(char *cmd, int l);
void Echo(char **a);
char *Pwd();
void Cd(char **a);
int g;
extern char **environ;
// Main function
void main()
{
system("clear");
char ch = '\n';
printf("\n\n\n*********************** SIMPLE SHELL *********************** \n");
while(1)
{
if(ch == '\n')
{
shell();
}
else
{
break;
}
ch = getchar();
}
}
// Shell function that takes user input
void shell()
{
char cmd[100];
char **a;
char *c = Pwd();
printf("\n\nSimpleShell:(%s)$ ",c);
scanf("%[^\n]s",cmd);
int l = strlen(cmd);
a = tok(cmd, l);
if(strcmp("cd", a[0]) == 0)
{
Cd(a);
}
else if(strcmp("echo", a[0]) == 0)
{
Echo(a);
}
else if(strcmp("pwd", a[0]) == 0 && a[1] == NULL)
{
c = Pwd();
printf("%s\n",c);
}
else
{
Cmd(a);
}
printf("\n\n************************************************************* \n");
free(a);
}
// Command function
void Cmd(char **a)
{
int status;
int cpid = fork();
char *cmd = a[0];
if(cpid == 0)
{
int z = execvp(cmd, a);
if(z != 0)
{
perror("Error ");
}
exit(0);
}
else
{
wait(&status);
}
}
// Token function
char **tok(char *cmd, int l)
{
char delim[] = " ";
char **token = malloc(l*sizeof(char *));
g = 0;
token[g] = strtok(cmd, delim);
while(token[g] != 0)
{
g++;
token[g] = strtok(0, delim);
}
return token;
}
// Echo function
void Echo(char **a)
{
char b[100] = "";
for(int i=1; i<g; i++)
{
strcat(b, a[i]);
strcat(b, " ");
}
int k = strlen(b);
for(int i=0; i<k; i++)
{
if(b[i] == '"')
{
for(int j=i; j<k; j++)
{
b[j] = b[j+1];
}
}
}
printf("%s\n",b);
}
// Pwd function
char *Pwd()
{
char *c = malloc(100*sizeof(char *));
getcwd(c, 100);
return c;
}
// Cd function
void Cd(char **a)
{
char *t;
if(a[1] == NULL || strcmp(a[1], "~") == 0)
{
chdir(getenv("HOME"));
}
else
{
chdir(a[1]);
t = Pwd();
printf("directory changed to %s\n",t);
}
}