-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecute.c
83 lines (76 loc) · 1.35 KB
/
execute.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
#include "hsh.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
/**
* execute - execute a program with arguments
*
* @ctx: shell context
*
* Return: 0 on success, 1 on command not found, -1 on failure
*/
int execute(context_t *ctx)
{
char *bin;
pid_t child_pid;
int status = 0;
char **env = to_array(ctx->env);
bin = which(*ctx->cmd->args, ctx);
if (bin == NULL)
{
free_array(env);
free(bin);
return (1);
}
child_pid = fork();
if (child_pid == -1)
{
free(bin);
return (-1);
}
else if (child_pid == 0)
{
if (execve(bin, ctx->cmd->args, env) == -1)
_exit(EXIT_FAILURE);
}
else
{
if (wait(&status) == -1)
{
free_array(env);
free(bin);
return (-1);
}
ctx->status = WEXITSTATUS(status);
}
free_array(env);
free(bin);
return (0);
}
/**
* exec_builtin - execute a built in command
*
* @ctx: shell context
*
* Return: 0 on success, -1 failure
*/
int exec_builtin(context_t *ctx)
{
int i = 0;
builtin_t bltns[] = {
{"env", builtin_env},
{"exit", builtin_exit},
{"setenv", builtin_setenv},
{"unsetenv", builtin_unsetenv},
{"cd", builtin_cd},
{"alias", builtin_alias},
{NULL, NULL}
};
if (ctx->cmd->args == NULL)
return (-1);
for (; bltns[i].name != NULL; i++)
if (_strcmp(bltns[i].name, *ctx->cmd->args) == 0)
return (bltns[i].f(ctx));
return (-1);
}