-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscriptandtoke.c
114 lines (104 loc) · 1.99 KB
/
scriptandtoke.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
104
105
106
107
108
109
110
111
112
113
114
#include "shell.h"
/**
* _strtok - Returns next word of input string
* @str: The input string
* @index: Where we are in the input string
* @delim: Spaces, null bytes, semicolons
* Return: Next word of input string
*/
char *_strtok(char *str, int *index, char delim)
{
int x = 0, y = 0;
char *tok = NULL;
if (!str)
return (NULL);
while (str[(*index)] == ' ')
{
if (str[(*index)] == ' ' && str[(*index) + 1] == '\0')
return (NULL);
(*index)++;
}
while (str[y + (*index)] != '\0' && str[y + (*index)] != delim)
y++;
tok = malloc(sizeof(char) * (y + 1));
if (!tok)
return (NULL);
for (x = 0; x < y; x++)
tok[x] = str[x + (*index)];
tok[x] = '\0';
*index += x;
return (tok);
}
/**
* _script - runs command script
* @fd: File descriptor for script
* @argv: Arguments
* @env: Environment
* @my_lists: lists for env and aliases
* Return: void
*/
my_ret _script(int fd, char *argv, char **env, my_ret my_lists)
{
int x = 0, xx = 0, buflen = 0, newlen = 0;
char *buf = NULL, tmp[1024];
char **Cmd = NULL;
ssize_t count;
while ((count = read(fd, tmp, 1024)) > 0)
{
if (buf != NULL)
buflen = _strlen(buf);
newlen = buflen + count;
buf = _realloc(buf, buflen, newlen + 1);
for (x = 0; x < count; x++)
{
buf[xx] = tmp[x];
xx++;
}
buf[xx] = '\0';
}
if (!buf)
exit(0);
for (x = 0; buf[x]; x++)
{
if (buf[x] == '\n')
buf[x] = ';';
}
if (x != 0)
{
Cmd = parser1(buf, argv);
free(buf);
my_lists = parser2(Cmd, argv, env, my_lists);
for (x = 0; Cmd[x]; x++)
free(Cmd[x]);
free(Cmd);
}
return (my_lists);
}
/**
* exec_Cmd - execute function
* @tokes: 2d array of tokens
* @argv: argv[0]
* @env: environment
* Return: void
*/
void exec_Cmd(char **tokes, char *argv, char **env)
{
pid_t pid = fork();
int err_num;
(void)env;
if (pid != 0)
{
while (wait(NULL) != -1)
;
kill(pid, SIGKILL);
}
else
{
if (execve(tokes[0], tokes, NULL) == -1)
{
err_num = errno;
handle_err(argv, err_num, tokes[0]);
_exit(127);
}
}
}