-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell_main.cpp
90 lines (74 loc) · 1.72 KB
/
shell_main.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
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
void parse_arg(char* arg, char* argv[], char input[]) //Function to parse the command input into args
{
char shell[256];
getcwd(shell, 255);
cout << shell << ":~$ ";
cin.getline(input,50);
arg = strtok(input, " ");
int i = 0;
while(arg != NULL)
{
argv[i] = arg;
i++;
arg = strtok(NULL, " ");
}
}
void exec_arg(char* argv[]) //Function used to execute the argument through fork and exec
{
pid_t pid;
pid = fork();
switch(pid)
{
case -1:
cout << "DEBUG:Fork Failure" << endl;
exit(-1);
case 0:
execvp(argv[0], argv);
if(execvp(argv[0], argv) == -1)
{
cout << "Command Not Found: " << argv[0] << endl;
exit(0);
}
default:
wait(NULL);
cout << endl << "Shell Process Finished" << endl;
}
}
void clean_arry(char* argv[]) //Empties the arv array for the next command
{
for(int i=0; i < 40; i++){argv[i] = NULL;}
}
int main()
{
char* arg;
char* argv[40];
char input[50];
while(argv[0] != NULL) //Implementation for an exit of the CLI
{
clean_arry(argv);
parse_arg(arg, argv, input);
if(strcmp(argv[0], "exit") == 0 || strcmp(argv[0], "quit") == 0 )
{
break;
}
else if(strcmp(argv[0],"cd") == 0) //Implementation to change the directory working in
{
chdir(argv[1]);
wait(NULL);
cout << endl << "Shell Process Finished" << endl;
}
else
{
exec_arg(argv);
}
}
return 1;
}