-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshell_input_exec.c
137 lines (123 loc) · 2.12 KB
/
shell_input_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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include "holberton.h"
/**
* shell_exec - forks and executes files in child process
*
* @cash: Shell variable struct
*
* Return: void
*/
void shell_exec(struct shell cash)
{
pid_t c_id;
int status;
if (access(cash.name, X_OK) == -1)
{
shell_error(cash, 3);
exit(99);
}
c_id = fork();
if (c_id == -1)
{
perror("Error:");
exit(1);
}
else if (c_id == 0 && cash.exec == 0)
{
if (execve((cash.p_buf)[0], cash.p_buf, NULL) == -1)
{
shell_error(cash, 1);
free(cash.i_buf);
free(cash.p_buf);
exit(1);
}
}
else if (c_id == 0 && cash.exec == 1)
{
if (execve(cash.rel, cash.p_buf, NULL) == -1)
{
shell_error(cash, 1);
free(cash.i_buf);
free(cash.p_buf);
exit(1);
}
}
else
wait(&status);
}
/**
* shell_env - prints environment
* @cash: Shell variable struct
*
* Return: void
*/
void shell_env(struct shell cash)
{
char *buf, new[] = {'\n', '\0'};
int i = 0;
for ( ; (buf = cash.env[i]) != NULL ; i++)
{
write(0, buf, _strlen(buf));
write(0, new, 1);
}
}
/**
* shell_exit - exits shell with exit code upon invocation
*
* @cash: Shell variable struct
*
* Return: void
*/
void shell_exit(struct shell cash)
{
int stat = 0, i;
if ((cash.p_buf)[1])
{
for (i = 0 ; (cash.p_buf)[1][i] != '\0'; i++)
{
if ((cash.p_buf)[1][i] <= '9' &&
(cash.p_buf)[1][i] >= '0')
{
stat = (stat * 10) + ((cash.p_buf)[1][i] - '0');
}
else
{
shell_error(cash, 2);
return;
}
}
free(cash.i_buf);
free(cash.p_buf);
exit(stat);
}
else
{
free(cash.i_buf);
free(cash.p_buf);
exit(0);
}
}
/**
* input_exec - calls functions based on passed string array
*
* @cash: Shell variable struct
*
* Description: Execute main. This function looks at the first values of the
* array and uses a switch (for now) to determine what function pointer
* to return.
*
* Return: pointer to function
*/
void (*input_exec(struct shell cash))(struct shell)
{
exec array[] = {
{"exit", shell_exit},
{"env", shell_env},
{NULL, direct_path}
};
int i = 0;
while (array[i].cmd && _strcmp(array[i].cmd, (cash.p_buf)[0]))
{
i++;
}
return (array[i].fun);
}