-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecute.c
More file actions
83 lines (80 loc) · 1.79 KB
/
Copy pathexecute.c
File metadata and controls
83 lines (80 loc) · 1.79 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
#include "main.h"
/**
* Executefile - executes the specified file.
* @command_line: the file to execute.
* @programName: the first argv of main.
* Return: the status of the last process.
*/
int Executefile(char *command_line, char *programName)
{
pid_t pid;
char **args = NULL, **env = environ, *path;
int num_args, stat = 0;
if (*command_line != '\0' && *command_line != '#')
{
command_line = findComment(command_line);
num_args = countArguments(command_line);
args = createBuffer(num_args, command_line);
path = full_path(args[0]);
if (path != NULL)
{
pid = fork();
if (pid == 0)
{
execve(path, args, env);
perror(args[0]);
}
else if (pid > 0)
waitpid(pid, &stat, 0);
else
perror("fork");
}
else
{
write(STDERR_FILENO, programName, strlen(programName));
write(STDERR_FILENO, ": 1: ", 5);
write(STDERR_FILENO, args[0], strlen(args[0]));
write(STDERR_FILENO, ": not found\n", 12);
}
if (path != args[0])
free(path);
customFree(args);
}
return (stat);
}
/**
* full_path - provides the full path of a file
* @file_name: the file to look for
* Return: pointer to the path of the file
*/
char *full_path(char *file_name)
{
char path[BUFF_SIZE], *ptr_path, **env = environ, *paths, *f_paths;
int i = 0;
if (access(file_name, F_OK) == 0)
return (file_name);
while (env[i] != NULL)
{
if (_strncmp(env[i], "PATH=", 5) == 0)
{
paths = _strdup(env[i] + 5);
f_paths = strtok(paths, ":");
while (f_paths)
{
ptr_path = _strcpy(path, f_paths);
ptr_path = _strcat(path, "/");
ptr_path = _strdup(_strcat(path, file_name));
if (access(ptr_path, X_OK) == 0)
{
free(paths);
return (ptr_path);
}
free(ptr_path);
f_paths = strtok(NULL, ":");
}
free(paths);
}
i++;
}
return (NULL);
}