-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexecute.c
68 lines (61 loc) · 1.14 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
#include "shell.h"
/**
* _execute - Executes a command in a child process.
* @command: An array of strings representing the command and its arguments.
* @argv: An array of strings representing the command line arguments.
* @idx: The index of the command in the input.
*
* Return: The exit status of the executed command.
*/
int _execute(char **command, char **argv, int idx)
{
char *full_cmd;
pid_t child;
int status;
full_cmd = _getpath(command[0]);
if (!full_cmd)
{
print_error(argv[0], command[0], idx);
freearray2D(command);
return 127;
}
child = fork();
if (child == -1)
{
perror("fork");
free(full_cmd);
freearray2D(command);
return -1;
}
if (child == 0)
{
if (execve(full_cmd, command, environ) == -1)
{
perror("execve");
free(full_cmd);
freearray2D(command);
exit(EXIT_FAILURE);
}
}
else
{
if (waitpid(child, &status, 0) == -1)
{
perror("waitpid");
free(full_cmd);
freearray2D(command);
return -1;
}
}
freearray2D(command);
free(full_cmd);
if (WIFEXITED(status))
{
return WEXITSTATUS(status);
}
else
{
perror("Child process did not terminate normally");
return -1;
}
}