-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexternal_command.c
More file actions
65 lines (56 loc) · 1.51 KB
/
external_command.c
File metadata and controls
65 lines (56 loc) · 1.51 KB
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
#include "shell.h"
/**
* execute_external_command - Executes an external command.
* @input: The command to be executed.
*/
void execute_external_command(char *input)
{
pid_t pid = fork();
if (pid == -1)
{
perror("fork");
}
else if (pid == 0)
{
char *path = getenv("PATH");
char *token = str_tok(path, ":");
char **args = NULL;
char *env[] = {NULL};
while (token != NULL)
{
char full_path[MAX_INPUT_SIZE];
snprintf(full_path, sizeof(full_path), "%s/%s", token, input);
printf("Full path: %s\n", full_path);
if (access(full_path, F_OK | X_OK) == 0)
{
args = malloc(2 * sizeof(char *));
if (args == NULL)
{
perror("malloc");
_exit(EXIT_FAILURE);
}
args[0] = input;
args[1] = NULL;
if (exec_cmd(full_path, args, env) == -1)
{
perror(full_path);
free(args);
_exit(EXIT_FAILURE);
}
}
token = strtok(NULL, ":");
}
printf("%s: command not found\n", input);
free(args);
_exit(EXIT_FAILURE);
}
else
{
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
{
printf("%s: command not found\n", input);
}
}
}