-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexec_lib.c
More file actions
98 lines (89 loc) · 2.08 KB
/
exec_lib.c
File metadata and controls
98 lines (89 loc) · 2.08 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
#include "hsh.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
/**
* execute_command - executes a command
* @env: environment variables and tokens
* Return: void
*/
void execute_command(env_t *env)
{
pid_t pid;
int status;
char *cmd_path;
char *alias;
if (env->token_arr[0] == NULL || env->token_arr[0][0] == '\0' ||
env->token_arr[0][0] == '\n')
return;
if (builtin_mux(env->token_arr[0]) != NULL)
{
builtin_mux(env->token_arr[0])(env);
return;
}
alias = excualias(env, env->token_arr[0]);
if (alias)
env->token_arr[0] = alias;
cmd_path = get_path(env->token_arr[0], env->env);
if (cmd_path == NULL)
{
exit_error(env->argv[0], 1, env->token_arr[0], "not found", 127, NULL,
env);
return;
}
pid = fork();
if (pid == 0) /* child process */
{
if (execve(cmd_path, env->token_arr, env->env) == -1)
{
exit_error(env->argv[0], 1, "", "", 127, NULL, env);
free(cmd_path);
return;
}
exit(EXIT_FAILURE);
} /* clang-format off */
do { /* clang-format on */
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
free(cmd_path);
env->last_exit_status = WEXITSTATUS(status);
}
/**
* get_path - gets the path of a command
* @command: command to get path of
* @env: environment variables
* Return: path of command or the same command if it is already a path
* or NULL if not found
*/
char *get_path(char *command, char **env)
{
char *path;
char *token;
char *full_path;
if (command == NULL)
return (NULL);
if (command[0] == '/' || command[0] == '.')
return (_strdup(command));
path = _getenv("PATH", env);
if (path == NULL || path[0] == '\0' || path[0] == '\n')
return (NULL);
token = _strtok(path, ":");
while (token != NULL)
{
full_path = malloc(sizeof(char) * (_strlen(token) + _strlen(command) + 2));
if (full_path == NULL)
return (NULL);
_strcpy(token, full_path);
_strcat(full_path, "/");
_strcat(full_path, command);
if (access(full_path, X_OK) == 0)
{
free(path);
return (full_path);
}
free(full_path);
token = _strtok(NULL, ":");
}
free(path);
return (NULL);
}