forked from thenoblet/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute_command.c
More file actions
50 lines (45 loc) · 897 Bytes
/
execute_command.c
File metadata and controls
50 lines (45 loc) · 897 Bytes
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
#include "shell.h"
/**
* execute_command - Executes a shell command using fork and execve.
*
* @command: The command to execute.
*
* @lsh: Pointer to the shell structure containing relevant information.
*
* Return: Exit status of the executed command or -1 on failure.
*/
int execute_command(const char *command, shell_t *lsh)
{
int status;
pid_t pid = fork();
if (pid == -1)
handle_error("fork failed");
if (pid == 0)
{
if (execve(command, lsh->tokenized_commands, environ) == -1)
{
if (errno == EACCES)
{
fprintf(stderr, "%s: %lu: %s\n", lsh->prog_name, lsh->cmd_count,
strerror(errno));
return (127);
}
perror("execve");
return (-1);
}
}
else
{
if (waitpid(pid, &status, 0) == -1)
{
perror("wait");
return (-1);
}
if (WIFEXITED(status))
{
/* normal termination */
return (WEXITSTATUS(status));
}
}
return (0);
}