-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute_command.c
More file actions
53 lines (49 loc) · 1020 Bytes
/
execute_command.c
File metadata and controls
53 lines (49 loc) · 1020 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
51
52
53
#include "simple_shell.h"
/**
* execute_command - Execute a command.
* @command: The command to be executed.
* @args: Command arguments.
*
* This function creates a child process to execute the specified command.
* It uses the execve system call to replace the child process image with
* the specified command.
*/
void execute_command(char *command, char **args)
{
pid_t child_pid;
int child_status;
child_pid = fork();
if (child_pid == -1)
{
perror("fork");
_exit(EXIT_FAILURE);
}
else if (child_pid == 0)
{
char *full_path;
if (command[0] == '/' || command[0] == '.')
{
/* handle absolute/ relative paths */
full_path = strdup(command);
}
else
{
full_path = handle_path(command);
}
if (full_path == NULL)
{
fprintf(stderr, "Command not found: %s\n", command);
_exit(EXIT_FAILURE);
}
if (execve(full_path, args, environ) == -1)
{
perror("execve");
free(full_path);
_exit(EXIT_FAILURE);
}
}
else
{
waitpid(child_pid, &child_status, 0);
}
}