-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.c
74 lines (61 loc) · 1.85 KB
/
main.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
#include "main.h"
int main(int ac, char **argv)
{
char *prompt = "(Eshell) $ ";
char *lineptr = NULL, *lineptr_copy = NULL;
size_t n = 0;
ssize_t nchars_read;
const char *delim = " \n";
int num_tokens = 0;
char *token;
int i;
/* declaring void variables */
(void)ac;
/* Create a loop for the shell's prompt */
while (1)
{
printf("%s", prompt);
nchars_read = getline(&lineptr, &n, stdin);
/* check if the getline function failed or reached EOF or user use CTRL + D */
if (nchars_read == -1)
{
printf("Exiting shell....\n");
return (-1);
}
/* allocate space for a copy of the lineptr */
lineptr_copy = malloc(sizeof(char) * nchars_read);
if (lineptr_copy == NULL)
{
perror("tsh: memory allocation error");
return (-1);
}
/* copy lineptr to lineptr_copy */
strcpy(lineptr_copy, lineptr);
/********** split the string (lineptr) into an array of words ********/
/* calculate the total number of tokens */
token = strtok(lineptr, delim);
while (token != NULL)
{
num_tokens++;
token = strtok(NULL, delim);
}
num_tokens++;
/* Allocate space to hold the array of strings */
argv = malloc(sizeof(char *) * num_tokens);
/* Store each token in the argv array */
token = strtok(lineptr_copy, delim);
for (i = 0; token != NULL; i++)
{
argv[i] = malloc(sizeof(char) * strlen(token));
strcpy(argv[i], token);
token = strtok(NULL, delim);
}
argv[i] = NULL;
/* execute the command */
execmd(argv);
}
/* free up allocated memory */
free(lineptr_copy);
free(lineptr);
return (0);
}