-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_shell.c
More file actions
74 lines (68 loc) · 1.35 KB
/
simple_shell.c
File metadata and controls
74 lines (68 loc) · 1.35 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
65
66
67
68
69
70
71
72
73
74
#include "main.h"
/**
* handle_comment - Handle comment in command
* @line: line of code (set of commands)
*/
void handle_comment(char *line)
{
int i;
for (i = 0; line[i] != '\0'; i++)
{
if (line[i] == '#' && (line[i - 1] == ' ' || line[i + 1] == ' '))
{
line[i] = '\0';
break;
}
}
}
/**
* main - entry point
* Return: always 0
*/
int main(int ac, char **argv)
{
char *line = NULL, *line_copy = NULL, *token;
size_t len = 0;
ssize_t read_chars = 0;
const char *delim = " \n";
int count_token = 0, i;
(void)ac;
while (1)
{
write(0, "$ ", 2);
read_chars = getline(&line, &len, stdin);
if (read_chars == -1)
{
break;
}
handle_comment(line);
line_copy = malloc(sizeof(char) * read_chars);
if (line_copy == NULL)
{
perror("tsh: memory allocation error");
return (-1);
}
_strcpy(line_copy, line);
token = _strtok(line, delim);
while (token != NULL)
{
count_token++;
token = _strtok(NULL, delim);
}
count_token++;
argv = malloc(sizeof(char *) * count_token);
token = strtok(line_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;
run_command(argv);
count_token = 0;
}
free(line_copy);
free(line);
return (0);
}