-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec.c
91 lines (81 loc) · 1.54 KB
/
exec.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
#include "shell.h"
/**
* execute_command - executes a command with arguments
* @argv: array of command and arguments
*
* Return: 0 on success, 1 on failure
*/
int execute_command(char **argv)
{
char *cmd_path = argv[0];
pid_t child_pid;
size_t ishandlepath = 0;
if (access(cmd_path, X_OK) != 0)
{
cmd_path = handle_path(cmd_path);
ishandlepath = 1;
}
if (cmd_path == NULL)
{
perror("Command not found");
return (-1);
}
child_pid = fork();
if (child_pid == -1)
{
perror("fork error");
return (-1);
}
if (child_pid == 0)
{
char *envp[] = {NULL};
if (execve(cmd_path, argv, envp) == -1)
{
perror("execve error");
}
}
else
{
int status;
wait(&status);
}
if (ishandlepath)
free(cmd_path);
return (0);
}
/**
* handle_path - returns fullpath of command passed
* @cmd: command passed
*
* Return: return fullpath of command passed
*/
char *handle_path(char *cmd)
{
char *path = _getenv("PATH");
char *path_copy;
char *token;
char *full_path;
size_t full_path_len = 0;
path_copy = _strdup(path);
if ((path == NULL) || (path_copy == NULL))
{
perror("PATH not found");
return (NULL);
}
token = strtok(path_copy, ":");
full_path_len = _strlen(token) + _strlen(cmd) + 2;
full_path = malloc(sizeof(char) * full_path_len);
while (token)
{
/*concatenate the token in PATH with the command passed*/
full_path = _strcat(full_path, token, cmd, '/');
if (access(full_path, X_OK) == 0)
{
free(path_copy);
return (full_path);
}
token = strtok(NULL, ":");
}
free(path_copy);
return (NULL);
}