-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_getline.c
96 lines (88 loc) · 1.83 KB
/
_getline.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
#include "shell.h"
/**
* _getline - Reads the command from STDIN and tokenizes it
*
* Return: The tokenized command or NULL at files
*/
char **_getline(void)
{
char buf[4096], **command = NULL, *buffer = NULL;
int i = 0, k = 0;
do {
if (read(STDIN_FILENO, buf + i, 1) == 0)
{
if (i-- == 0)
{
write(STDOUT_FILENO, "\n", 1);
exit(0);
}
}
} while (*(buf + ++i - 1) != 10);
if (*buf == 10)
return (NULL);
*(buf + i - 1) = 0;
k = i;
for (i = 0; *(buf + i) != 0; i++)
{
if (*(buf + i) != 32 && *(buf + i) != 10)
break;
else if (*(buf + i + 1) == 0)
return (NULL);
}
buffer = malloc(k * sizeof(char));
if (buffer == NULL)
return (NULL);
for (i = 0; *(buf + i); i++)
*(buffer + i) = *(buf + i);
*(buffer + i) = 0;
command = _strtok(buffer, 32);
if (command == NULL)
return (NULL);
free(buffer);
buffer = NULL;
return (command);
}
/**
* _getline_NIM - Reads the command from STDIN and tokenizes it
*
* Return: The tokenized command or NULL at files
*/
char **_getline_NIM(void)
{
char buf[8192], **command_token = NULL, **command = NULL, *buffer;
int i = 0, k = 0;
pid_t child_detect;
while (read(STDIN_FILENO, buf + i, 1))
i++;
*(buf + i) = 0;
k = i;
for (i = 0; *(buf + i) != 0; i++)
if (*(buf + i) != 32 && *(buf + i) != 10)
break;
else if (*(buf + i + 1) == 0)
return (NULL);
buffer = _calloc((k + 1), sizeof(char));
if (buffer == NULL)
return (NULL);
for (i = 0; i < k; i++)
*(buffer + i) = *(buf + i);
*(buffer + i) = 0;
command_token = _strtok(buffer, 10);
free(buffer);
for (i = 0; *(command_token + i); i++)
{
child_detect = fork();
wait(NULL);
if (child_detect == 0)
{
command = _strtok(*(command_token + i), 32);
if (command == NULL)
return (NULL);
break;
}
}
free_dp(command_token);
if (child_detect != 0)
exit(0);
return (command);
}