|
1 | 1 | #include "header.h"
|
2 | 2 |
|
3 | 3 | /**
|
4 |
| - * _execute - code that executes the execve commands |
5 |
| - * @args: pointer to string array |
6 |
| - * @envp: array to pointer of environment variable |
| 4 | + * execute_command - function to handle command execution based on user input |
| 5 | + * @get_address: input line from user |
| 6 | + * @env: environment variable |
7 | 7 | *
|
8 |
| - * Return: 0 successful |
| 8 | + * Return: output executed command else -1 |
9 | 9 | */
|
10 | 10 |
|
11 |
| -int _execute(char *args, char **envp) |
| 11 | +int execute_command(char *get_address, char __attribute__((__unused__)) **env) |
12 | 12 | {
|
13 |
| - char **argv; |
14 |
| - /*int kai;*/ |
15 |
| - struct stat buff; |
| 13 | + char *delim = " \n\t\r"; |
| 14 | + char **tokens = NULL, *command_path = NULL; |
| 15 | + int status = 0, ex = 0; |
16 | 16 |
|
17 |
| - argv = malloc(sizeof(char *)); |
18 |
| - if (argv == NULL) |
| 17 | + tokens = tokenize(get_address, delim); |
| 18 | + if (!tokens || tokens[0] == NULL) |
19 | 19 | {
|
20 |
| - perror("Error: "); |
21 |
| - exit(EXIT_FAILURE); |
| 20 | + perror("Error "); |
| 21 | + return (ex); |
22 | 22 | }
|
23 |
| - argv[0] = strtok(args, " \t\n"); |
24 |
| - if (argv[0] == NULL) |
| 23 | + if (_strcmp(tokens[0], "exit") == 0) |
25 | 24 | {
|
26 |
| - free(argv); |
27 |
| - return (0); |
| 25 | + if (tokens[1] != NULL) |
| 26 | + { |
| 27 | + status = atoi(tokens[1]); |
| 28 | + } |
| 29 | + free(tokens); |
| 30 | + free(command_path); |
| 31 | + exit(status); |
28 | 32 | }
|
29 |
| - /*check if file exists*/ |
30 |
| - if (stat(argv[0], &buff) == -1) |
| 33 | + if (_strcmp(tokens[0], "env") == 0) |
31 | 34 | {
|
32 |
| - perror("Error: "); |
33 |
| - free(argv); |
34 |
| - exit(EXIT_FAILURE); |
| 35 | + _printenv(); |
| 36 | + free(tokens); |
| 37 | + free(command_path); |
| 38 | + return (ex); |
35 | 39 | }
|
36 |
| - execve(argv[0], argv, envp); |
37 |
| - /*print error if execve failed*/ |
38 |
| - perror("Error execve:"); |
39 |
| - free(argv); |
40 |
| - exit(EXIT_FAILURE); |
| 40 | + command_path = locate_path(tokens[0]); |
| 41 | + if (!command_path) |
| 42 | + { |
| 43 | + perror("command not found"); |
| 44 | + free(tokens); |
| 45 | + ex = 127; |
| 46 | + return (ex); |
| 47 | + } |
| 48 | + execute_and_wait(command_path, tokens, &ex); |
| 49 | + return (ex); |
41 | 50 | }
|
0 commit comments