-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.c
104 lines (96 loc) · 1.9 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "shell.h"
/**
* main - Entry point for the shell program
*
* Return: Returns 0 on success, or status of the non_interactive_mode
*/
int main(void)
{
size_t size_line = 0;
char *line = NULL;
int status = 0;
if (!isatty(0))
{
while (getline(&line, &size_line, stdin) != -1)
{
non_interactive_mode(line, &status);
}
if (line)
{
free(line);
line = NULL;
}
return (status);
}
debut_shell();
return (0);
}
/**
* non_interactive_mode - Executes shell commands in non_nteractive_mode
* @token: The string containing commands separated by newline characters
* @status: integer store the number
* Return: Returns status.
*/
void non_interactive_mode(char *token, int *status)
{
char **single_command;
char *envp[] = {NULL};
token[strlen(token) - 1] = '\0';
single_command = tokenize_string(token, " \t");
if (single_command[0])
{
if (!_strcmp(single_command[0], "exit"))
{
if (single_command[1])
{
int my_status = _atoi(single_command[1]);
handle_exit_status(my_status, single_command, &token, status);
}
else
{
free(token);
free_array(single_command);
exit(*status);
}
}
else if (!_strcmp(single_command[0], "env"))
{
print_env_var();
*status = 0;
}
else
_execvep(single_command, envp, status);
}
free_array(single_command);
}
/**
* tokenize_string - Splits a string into tokens
* @str: The string to tokenize
* @delimiters: The delimiters to use for tokenization
*
* Return: Returns result.
*/
char **tokenize_string(char *str, char *delimiters)
{
int count = 0;
char *token;
char **result = malloc(20 * sizeof(char *));
if (result == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
token = strtok(str, delimiters);
while (token != NULL)
{
result[count] = _strdup(token);
count++;
token = strtok(NULL, delimiters);
}
while (count < 20)
{
result[count] = NULL;
count++;
}
return (result);
}