-
Notifications
You must be signed in to change notification settings - Fork 1
/
16.c
97 lines (87 loc) · 2.85 KB
/
16.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
#include <errno.h> // Definition for "error handling"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h> // Definition for wait()
#include <unistd.h> // Definition for fork() and execve()
/* Declarations for getline() */
char * input = NULL;
size_t capline = 0; // Capacity
/* Declaration for strtok() */
int i;
char *token;
char *array[512];
/* Display some info to the user at the start */
void startDisplay()
{
printf("**************************************************************\n");
printf("*WELCOME TO THE COMMAND LINE INTERPETER *\n");
printf("*TO RUN A COMMAND SIMPLY TYPE YOUR COMMAND AND PRESS 'ENTER' *\n");
printf("*EXAMPLE: ls -a, <any linux cmd> *\n");
printf("*Additional: count c/w/l <filename> *\n");
printf("*TO EXIT TYPE 'q' || 'exit' *\n");
printf("**************************************************************\n");
}
/* Print out "MY_SHELL" */
void displayPrompt()
{
printf("NewShell$ ");
}
/* Divide input line into tokens */
void makeTokens(char *input)
{
i = 0;
token = strtok(input, "\n ");
while (token != NULL) {
array[i++] = token; // Add tokens into the array
token = strtok(NULL, "\n ");
}
array[i] = NULL;
}
/* Execute a command */
void execute()
{
int pid = fork(); // Create a new process
if (pid != 0) { // If not successfully completed
int s;
waitpid(-1, &s, 0); // Wait for process termination
}
else {
if (execvp(array[0], array) == -1) { // If returned -1 => something went wrong! If not then
// command successfully completed */
perror("Wrong command"); // Display error message
exit(errno);
}
}
}
int main()
{
startDisplay();
while (1) {
displayPrompt(); // Display a user prompt
getline(&input, &capline, stdin); // Read the user input
if (strcmp(input, "\n") == 0) {
perror("Please type in a command ");
continue;
}
makeTokens(input); // Divide line into tokens
if (strcmp(array[0], "count") == 0) {
array[0] = "wc";
if (strcmp(array[1], "c") == 0) {
array[1] = "-c";
}
else if (strcmp(array[1], "l") == 0) {
array[1] = "-l";
}
else if (strcmp(array[1], "w") == 0) {
array[1] = "-w";
}
}
/* Check if input is "q" | "exit", if yes then exit shell */
if ((strcmp(array[0], "q") == 0) || (strcmp(array[0], "exit") == 0)) {
printf("SYSTEM : Shell is exit\n");
return 0;
}
execute(); // Call execvp()
}
}