-
Notifications
You must be signed in to change notification settings - Fork 0
/
com_misc1.c
124 lines (117 loc) · 2.53 KB
/
com_misc1.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
#include "main.h"
/**
* exit_exec - handles error and freeing tokens and buffer on execve failure
* @tokens: 2D pointer to the array of tokens
* @n_tok: number of tokens
* @buffer: pointer to the buffer to free
* @path: the path
* @iter: current iteration
* Return: No return
*/
void exit_exec(char **tokens, int n_tok, char *buffer, char *path, UINT iter)
{
free(path);
print_err(iter, "", "");
perror("");
free_grid(tokens, n_tok);
free(buffer);
exit(errno);
}
/**
* not_found - handles error and freeing tokens and buffer on execve failure
* @tokens: 2D pointer to the array of tokens
* @n_tok: number of tokens
* @iter: current iteration
* Return: No return
*/
void not_found(char **tokens, int n_tok, UINT iter)
{
/*perror(_getenv("_"));*/
errno = 127;
print_err(iter, tokens[0], "not found\n");
free_grid(tokens, n_tok);
}
/**
* handle_signal - soft exiting at a given signal (ex. CTRL+C)
* @sig: not used but useful
* Return: No return
*/
void handle_signal(int sig)
{
(void)sig;
_putchar('\n');
_puts(PROMPT);
}
/**
* _getenv - gets a variable from environment given its name
* @name: variable name
* Return: the variable and its value as a string.
*/
char *_getenv(const char *name)
{
int i = 0, len_name;
char *var = NULL, *tmp = NULL;
if (name == NULL)
return (NULL);
len_name = _strlen((char *)name);
tmp = _strdup((char *)name);
var = _strcat(tmp, "=");
free(tmp);
while (environ[i])
{
if (_strsearch(environ[i], var, 0) == 1)
{
free(var);
return (_substr(environ[i], len_name));
}
i++;
}
free(var);
return (NULL);
}
/**
* _which - checks the path of a command
* @cmd: the command to check
* Return: a pointer to the buffer holding the path, or NULL if no match
*/
char *_which(char *cmd)
{
int p, n_paths = 0, errno_cpy = errno;
char *env_path = NULL, *env_path_cpy = NULL;
char **paths = NULL, *path = NULL, *tmp = NULL, *tmp2 = NULL;
env_path = _getenv("PATH");
env_path_cpy = _strdup(env_path);
paths = tokenizer(env_path_cpy, ":");
free(env_path_cpy);
n_paths = ctokens(paths);
for (p = 0; p < n_paths; p++)
{
tmp = _strdup(paths[p]);
tmp2 = _strcat(tmp, "/");
free(tmp);
path = _strcat(tmp2, cmd);
free(tmp2);
if (access(path, X_OK) == 0)
{
free_grid(paths, n_paths);
errno = errno_cpy;
return (path);
}
else
free(path);
}
if (access(cmd, X_OK) == 0)
{
path = _strdup(cmd);
errno = errno_cpy;
if (is_path(path))
{
free_grid(paths, n_paths);
return (path);
}
free(path);
}
free_grid(paths, n_paths);
errno = errno_cpy;
return (NULL);
}