-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecute_command.c
More file actions
116 lines (109 loc) · 2.2 KB
/
Copy pathexecute_command.c
File metadata and controls
116 lines (109 loc) · 2.2 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "shell.h"
/**
* synchronus_child_execution - create & execute a child. Wait for termination
* @args: Array of arguments for the command to be executed
* @cmd_num: Command line number
* Return: Error code otherwise 0
*/
int synchronus_child_execution(char *args[], int cmd_num)
{ int ret = 0, ret_exec = 0, status = 0;
pid_t pid;
char *tmp = NULL;
char **_env = environ;
tmp = find_in_path(args[0]);
if (!tmp)
tmp = args[0];
if (tmp && access(tmp, F_OK) != -1)
{
if (access(tmp, X_OK) != -1)
{ pid = fork();
if (pid < 0)
{
return (1);
}
else if (pid == 0)
{ ret_exec = execve(tmp, args, _env);
exit(ret_exec);
}
else
{ wait(&status);
if (WIFEXITED(status))
ret = WEXITSTATUS(status); }
}
else
{ print_error_msg("Permission denied", args[0], cmd_num);
if (tmp != args[0])
free(tmp);
return (126);
}
}
else
{ print_error_msg("not found", args[0], cmd_num);
if (tmp != args[0])
free(tmp);
return (127);
}
if (tmp != args[0])
free(tmp);
return (ret);
}
/**
* my_strdup - function to duplicate a string
* @copy_str: string to duplicate
* Return: pointer to the duplicated string
*/
char *my_strdup(const char *copy_str)
{
char *ret = NULL;
size_t len = strlen(copy_str) + 1;
if (!copy_str)
return (NULL);
ret = malloc(len);
if (!ret)
return (NULL);
memcpy(ret, copy_str, len);
return (ret);
}
/**
* parse_cmd_line - function parses a command line and transform an array args
* @ret: pointer to an array that will receive the address of the array of args
* @cmd_line: String containing the command line to be parsed
* Return: the number of arguments
*/
int parse_cmd_line(char *cmd_line, char ***ret)
{
char *tmp = NULL;
int i = 0, size = 0;
char *copy = NULL;
*ret = NULL;
copy = strdup(cmd_line);
if ((*ret))
{
free(copy);
return (0);
}
if (!copy)
{
return (0);
}
tmp = strtok(copy, " \n");
while (tmp)
{ size++;
tmp = strtok(NULL, " \n");
}
size++;
*ret = (char **)malloc(sizeof(char *) * size);
if (!(*ret))
{ free(copy);
exit(0);
}
tmp = strtok(cmd_line, " \n");
while (tmp)
{ (*ret)[i] = my_strdup(tmp);
i++;
tmp = strtok(NULL, " \n");
}
(*ret)[i] = NULL;
free(copy);
return (size);
}