-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.c
More file actions
105 lines (93 loc) · 1.6 KB
/
shell.c
File metadata and controls
105 lines (93 loc) · 1.6 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
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
104
105
#include "main.h"
/**
* main - execve example
*
*@argc: number of arguments
*@argv: argument vectors
* Return: Always 0.
*/
int main(int argc, char **argv)
{
char *buffer, **array, c;
int counter = 0;
(void)argc;
while (1)
{
counter++;
if (isatty(STDIN_FILENO))
write(1, "$ ", 2);
buffer = _getline();
c = buffer[0];
if (c == '\0')
continue;
array = parser(buffer);
if (check_cmd(array[0]) == 0)
{
exec_builtin(array, counter, argv[0]);
free(array);
free(buffer);
array = NULL;
buffer = NULL;
continue;
}
else
execute(array, counter, argv, buffer);
free(array);
free(buffer);
}
return (0);
}
/**
*parser- parses the commmand input
*
*@buffer: string containing command
*
*Return: Parsed command
*/
char **parser(char *buffer)
{
char **cmd, *token;
int i;
if (buffer == NULL)
return (NULL);
token = strtok(buffer, " \n");
if (token == NULL)
return (NULL);
cmd = malloc(sizeof(char *) * 1024);
i = 0;
while (token)
{
cmd[i++] = token;
token = strtok(NULL, " \n");
}
cmd[i] = NULL;
return (cmd);
}
/**
*execute - executes commands within the shell
*
*@array: parsed command
*@counter: command no
*@argv: commandline arguments
*@buffer:buffer containing input
*/
void execute(char **array, int counter, char **argv, char *buffer)
{
int status;
if (fork() != 0)
{
wait(&status);
}
else
{
if (_strncmp(array[0], "./", 2) != 0 && _strncmp(array[0], "/", 1) != 0)
path_finder(&array[0]);
if (execve(*array, array, environ) == -1)
{
printE(counter, array[0], argv[0]);
free(array);
free(buffer);
exit(EXIT_FAILURE);
}
}
}