-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute_command.c
More file actions
107 lines (100 loc) · 2.09 KB
/
Copy pathexecute_command.c
File metadata and controls
107 lines (100 loc) · 2.09 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
#include "main.h"
#include <stdio.h>
/**
* execute_cmd - Executes built-in commands and also executes external commands
* @av: array of command arguments to be executed
* @env: our shells environment vairables
* @program: the program name
* Return: 0 on successful compilation and -1 on failure
*/
int execute_cmd(char **av, char **env, char *program)
{
int status = 0;
char *full_path = NULL;
char **avCpy = NULL;
if (av == NULL)
return (-1);
status = execute_builtins(av);
if (status != -1)
return (status); /*A builtin function is found*/
full_path = get_fullpath(av[0]);
if (full_path != NULL)
{
if (av[1] == NULL)
{
status = execute_external(full_path, av, env, program);
free(full_path);
return (status);
}
avCpy = &(av[0]);
status = execute_external(full_path, avCpy, env, program);
free(full_path);
return (status);
}
perror(program);
return (-1);
}
/**
* execute_builtins - Looks for matching built-in function and executes it
* @av: string array of command arguments to be executed
* Return: 1 on success and -1 on failure
*/
int execute_builtins(char **av)
{
int c = 0;
func_builtin builtIns[] = {
exit_builtin,
env_builtin
};
char *builtin_cmds[] = {
"exit",
"env",
NULL
};
for (c = 0; builtin_cmds[c] != NULL; c++)
{
if (_strcmp(av[0], builtin_cmds[c]) == 0)
{
return (builtIns[c](av));
}
}
return (-1);
}
/**
* execute_external - process gets created to execute a non-built-in command
* @full_path: absolute full path to the location of the program
* @av: string array of command arguments to be ran
* @env: machine environment variable
* @program: name of the program
* Return: 1 on successful compilation and exit on failure
*/
int execute_external(char *full_path, char **av, char **env, char *program)
{
int status = 0;
pid_t pid;
if (!full_path)
return (-1);
pid = fork();
if (pid == -1)
{
perror(program);
return (-1);
}
if (pid == 0)
{
if (execve(full_path, av, env) == -1)
{
perror(program);
exit(1);
}
}
else
{
if (wait(&status) == -1)
{
perror(program);
exit(-1);
}
}
return (1);
}