forked from kritika20sharma/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.cpp
More file actions
64 lines (57 loc) · 1.41 KB
/
shell.cpp
File metadata and controls
64 lines (57 loc) · 1.41 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
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
#include<string.h>
void read_command(char cmd[], char *par[]) {
char line[1024];
int count = 0, i = 0, j = 0;
char *array[100], *pch;
// Read one line
for (; ;) {
int c = fgetc(stdin);
line[count++] = (char) c;
if (c == '\n') break;
}
if (count == 1) return;
pch = strtok(line, "\n");
// parse the line into words
while (pch != NULL) {
array[i++] = strdup(pch);
pch = strtok(NULL, "\n");
}
// first word is the command
strcpy(cmd, array[0]);
// others are parameters
for (int j = 0; j < i; j++)
par[j] = array[j];
par[i] = NULL; // NULL-terminate the parameter list
}
void type_prompt() {
static int first_time = 1;
if (first_time) { // clear screen for the first time
const char* CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
first_time=0;
}
printf("#"); // display prompt
}
int main() {
char cmd[100], command[100], *parameters[20];
// environment variable
char *envp[] = { (char *) "PATH=/bin", 0 };
while (1) { // repeat forever - shell
type_prompt(); // display prompt on the screen
read_command(command, parameters); // read input from the user
if (fork() != 0) // parent
wait(NULL);
else {
strcpy(cmd, "/bin/");
strcat(cmd, command);
execve(cmd, parameters, envp); // execute command
}
if (strcmp(command, "exit") == 0)
break;
}
return 0;
}