forked from gstieg/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelperfunc.c
126 lines (119 loc) · 1.87 KB
/
helperfunc.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
115
116
117
118
119
120
121
122
123
124
125
126
#include "shell.h"
/**
* _strcmp - making our own string compare
*
* @str1: string 1
*
* @str2: string 2
*
* Return: _strcmp
*/
int _strcmp(char *str1, char *str2)
{
if (*str1 < *str2)
return (-1);
if (*str1 > *str2)
return (1);
if (*str1 == '\0')
return (0);
return (_strcmp(str1 + 1, str2 + 1));
}
/**
* _parseline - function to take string as input and break words up into tokens
*and save in an array of strings
*
*@buf: string recieved
*
*@delim: delim
*
*Return: pointer to new arrary of strings
*/
char **_parseline(char *buf, char *delim)
{
int i;
char *tokens;
char **args;
i = 0;
tokens = strtok(buf, delim);
args = malloc(sizeof(char *) * 1024);
{
if (args == NULL)
return (0);
}
while (tokens)
{
args[i] = tokens;
tokens = strtok(NULL, " ");
i++;
}
args[i] = NULL;
return (args);
}
/**
*_forkIt- function to create a child process and execute commands
*
*@str: string that contains command
*
*Return: void
*/
void _forkIt(char *str)
{
char **gg;
pid_t pid;
int status = 0, er = 0;
pid = fork();
if (pid == 0)
{
gg = _parseline(str, " ");
er = execve(gg[0], gg, environ);
if (er == -1)
{
write(STDERR_FILENO, gg[0], _strlen(gg[0]));
write(STDERR_FILENO, ": No such file or directory found \n", 36);
free(gg);
free(str);
exit(0);
}
}
if (pid > 0)
{
wait(&status);
}
}
/**
*_counter - function to count how many words a string has
*
*@buf: string to be parsedd
*@delim: delimiter used
*
*Return: number of words parsed
*/
int _counter(char *buf, char *delim)
{
int count;
char *tokens;
count = 1;
tokens = strtok(buf, delim);
while (tokens)
{
count++;
tokens = strtok(NULL, delim);
}
return (count);
}
/**
*_strlen- function to calculate the length of a string
*
*@s: given string
*
*Return: length of string
*/
int _strlen(char *s)
{
int r = 0;
while (s[r] != '\0')
{
r++;
}
return (r);
}