-
Notifications
You must be signed in to change notification settings - Fork 1
/
execute.c
122 lines (107 loc) · 1.56 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
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
#include "main.h"
/**
* _exec_ - execute command
* @args: arguments
* Return: 1 or -1
*/
int _exec_(char **args)
{
pid_t pid;
int status;
char **envp, *path;
path = determine_path(*args);
envp = returnenv();
if (args[0] == NULL)
return (-1);
if (_cmd_isvalid(*args) == 0) /* Validate Command */
{
pid = fork();
if (pid == 0)
{
if (execve(path, args, envp) == -1)
{
perror("Error executing command");
}
else
{
return (-1);
}
}
else if (pid < 0)
{
perror("Could not fork a new process");
}
else
{
while (!WIFEXITED(status) && !WIFSIGNALED(status))
waitpid(pid, &status, WUNTRACED);
wait(NULL);
return (-1);
}
}
else
{
perror("Invalid command ");
interactive();
}
free(path);
free(envp);
return (-1);
}
/**
* returnenv - returns environment variables
* Return: array
*/
char **returnenv(void)
{
int envC = 0;
char **env = environ;
char **envp = malloc(sizeof(char *) * BUFSIZE);
if (envp == NULL)
{
perror("Memory allocation error\n");
exit(EXIT_FAILURE);
}
while (*env != NULL)
{
envp[envC] = *env;
envC++;
env++;
}
envp[envC] = NULL;
return (envp);
}
/**
* _strcmp - compare strings
* @s1: first string
* @s2: second sring
* Return: 1 or -1 or 0
*/
int _strcmp(const char *s1, const char *s2)
{
while (*s1 != '\0' && *s2 != '\0')
{
if (*s1 > *s2)
{
return (1);
}
else if (*s1 < *s2)
{
return (-1);
}
s1++;
s2++;
}
if (*s1 == '\0' && *s2 == '\0')
{
return (0);
}
else if (*s1 == '\0')
{
return (-1);
}
else
{
return (1);
}
}