-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyShell.cpp
110 lines (87 loc) · 1.75 KB
/
myShell.cpp
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
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
void read_command(char *par[], bool isBackground)
{
char line[1024];
int count = 0;
for(;;)
{
int c = fgetc(stdin);
line[count++] = (char) c;
if (c == '\n') break;
}
//if(count == 1) return;
char *pch = strtok (line, " \n");
int i = 0;
while(pch != NULL)
{
if(strcmp(pch, "&") == 0)
{
isBackground = true;
}
else
{
par[i++] = pch;
}
pch = strtok(NULL, " \n");
i;
}
par[i] = 0;
}
void prompt()
{
//clearing the screen for the first time
static bool first_time = true;
if(first_time){
const char* CLEAR_SCREEN_ANSI = " \e[1;1H\e[2J";
write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
first_time = false;
}
int u = getuid();
//print $ for user and # for root
if(u = 0)
{
printf("myShell_# ");
}
else
{
printf("myShell_$ ");
}
}
int main()
{
while(1){
prompt();
bool isBackground = false;
char *par[20];
read_command(par, &isBackground);
if(strcmp(par[0], "exit") == 0){break;}
int pid = fork();
if(pid < 0)
{
fprintf(stderr, "Fork Failed\n");
}
else if (pid > 0 and !isBackground)
{
wait(NULL);
}
else if(pid > 0 and isBackground)
{
//send to bg
}
else
{
execvp(par[0], par);
}
}
return 0;
}