-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
67 lines (55 loc) · 1.18 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
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
void show_prompt(uid_t current_usr_id) {
if (current_usr_id == 0) {
printf("shell# ");
}
else {
printf("shell$ ");
}
}
void readInput(char * argv[], int * is_background) {
const int inputsize = 256;
char str[inputsize];
fgets(str, inputsize, stdin);
char * pch = strtok(str, " \n");
int i = 0;
while (pch != NULL) {
if (strcmp("&", pch) == 0) {
* is_background = 1;
}
else {
argv[i++] = pch;
}
pch = strtok(NULL, " \n");
}
argv[i++] = 0;
}
int main() {
uid_t id = getuid();
int status = 0;
while(1){
show_prompt(id);
int is_background = 0;
char * argv[10];
readInput(argv, &is_background);
int pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed");
return 1;
}
if (pid > 0 && is_background == 0) {
waitpid(pid, &status, 0);
}
else if (pid > 0 && is_background == 1) {}
else {
execvp(argv[0], argv);
fprintf(stderr, "Unable to execute bash command\n");
}
}
return 0;
}