-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.c
More file actions
126 lines (111 loc) · 2.26 KB
/
handler.c
File metadata and controls
126 lines (111 loc) · 2.26 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include "shell.h"
/**
* tokenize_path - tokenize the path dirs
* @path: path variable
* @name: name of program
* Return: array of directories in path
*/
char **tokenize_path(char *path, char *name)
{
int i = 0;
char **dirs = NULL;
char delim[] = ":";
char *token;
dirs = malloc(64 * sizeof(char *));
if (dirs == NULL)
error(name, 0, NULL, NULL, isatty(fileno(stdin)));
token = strtok(path, delim);
while (token != NULL)
{
dirs[i] = strdup(token);
token = strtok(NULL, delim);
i++;
}
dirs[i] = NULL;
return (dirs);
}
/**
* parse_path - parses the path variable
* @name: name of the program
* Return: an array containing the directories in path
*/
char **parse_path(char *name)
{
char *path = NULL;
char *path_copy;
char **dirs;
path = getenv("PATH");
if (path == NULL)
return (NULL);
path_copy = strdup(path);
dirs = tokenize_path(path_copy, name);
free(path_copy);
return (dirs);
}
/**
* Handle_path - handles path
* @args: executable array
* @buffer: input command
* @name: name of program
* @line: line number of command
* Return: the full path of the executable
*/
char *Handle_path(char **args, char *buffer, char *name, int line)
{
int i;
char *slash = "/", **folders = parse_path(name), *full_path = NULL;
if (folders == NULL)
{
free_arr(args);
error(name, line, buffer, "not found", isatty(fileno(stdin)));
}
if (check_executable(args[0]) == 0)
{
free_arr(folders);
return (args[0]);
}
i = 0;
while (folders[i] != NULL)
{
full_path = malloc(strlen(folders[i]) + strlen(args[0]) + 2);
if (full_path == NULL)
{
perror(name);
free_arr(folders);
return (NULL);
}
strcpy(full_path, folders[i]);
strcat(full_path, slash);
strcat(full_path, args[0]);
if (check_executable(full_path) == 0)
{
free_arr(folders);
return (full_path);
}
free(full_path);
i++;
}
if (folders != NULL)
free_arr(folders);
free_arr(args);
error(name, line, buffer, "not found", isatty(fileno(stdin)));
return (NULL);
}
/**
* check_executable - checks if a path is executable
* @path: path to the file
* Return: 0 or 1
*/
int check_executable(char *path)
{
if (access(path, X_OK) == 0)
{
struct stat st;
if (stat(path, &st) == 0)
{
if (S_ISREG(st.st_mode))
return (0);
}
}
return (1);
}