forked from amartinezre05/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_execve.c
98 lines (89 loc) · 1.5 KB
/
_execve.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
#include "simple_shell.h"
/**
* concat - concatenate strings
* @s1: pointer to args1
* @s2: pointer to args2
* Return: char result
*/
char *concat(char *s1, char *s2)
{
char *result = malloc(_strlen(s1) + _strlen(s2) + 1);
_strcpy(result, s1);
_strcat(result, s2);
return (result);
}
/**
* get_path - obtain path
* Return: void function.
*/
char *get_path(void)
{
char *var;
int i = 0;
while (environ[i])
{
var = _strtok(environ[i], "=");
if (!_strcmp(var, "PATH"))
{
return (_strtok(NULL, "="));
}
var = _strtok(NULL, "=");
i++;
}
return (NULL);
}
/**
* concat_path - concatenate path
* @args: double pointer to args
* Return: void function.
*/
char **concat_path(char **args)
{
char *path, **paths, *tok, *tmp;
int n = 0;
path = get_path();
tok = _strtok(path, ":");
paths = malloc(64 * sizeof(char *));
while (tok != NULL)
{
tmp = concat("/", args[0]);
paths[n] = concat(tok, tmp);
n++;
tok = _strtok(NULL, ":");
free(tmp);
}
paths[n] = NULL;
return (paths);
}
/**
* _execve - execute program
* @args: double pointer to args
* Return: void function.
*/
void _execve(char **args)
{
int n = 0, exist = 0;
char **path;
path = concat_path(args);
exist = access(args[0], F_OK | X_OK);
if (exist == -1)
{
while (path[n])
{
exist = access(path[n], F_OK | X_OK);
if (exist != -1)
{
args[0] = path[n];
break;
}
n++;
}
}
if (execve(args[0], args, environ) == -1)
{
perror("Error");
free_double(path);
free_double(args);
exit(127);
}
}