-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecute_command.c
More file actions
83 lines (81 loc) · 1.6 KB
/
execute_command.c
File metadata and controls
83 lines (81 loc) · 1.6 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
#include "shell.h"
#include <errno.h>
/**
* execute_command - Execute a command in a new process.
*
* @args: Arguments as a null-terminated array.
*
* Return: No return value.
*/
int execute_command(char **args)
{
pid_t child_pid;
int status = 0, flag = 0, i = 0;
char *fullPath = NULL;
struct stat st;
char **pathArr = NULL;
char *path = NULL;
if (stat(args[0], &st) == 0 && strcmp(args[0], "hbtn_ls") != 0)
{
fullPath = malloc(strlen(args[0]) * sizeof(char *));
strcpy(fullPath, args[0]);
flag = 1;
child_pid = fork();
}
else if (getenv("PATH") && strcmp(getenv("PATH"), "") != 0)
{
path = malloc(strlen(getenv("PATH")) * sizeof(char *));
strcpy(path, getenv("PATH"));
pathArr = parse_command(path, ":");
if (!path || !pathArr)
perror("malloc");
while (pathArr[i])
{
fullPath = malloc((strlen(pathArr[i]) + strlen(args[0]) + 1) * sizeof(char *));
strcpy(fullPath, pathArr[i]);
strcat(fullPath, "/");
strcat(fullPath, args[0]);
if (stat(fullPath, &st) == 0)
{
child_pid = fork();
flag = 1;
break;
}
free(fullPath);
i++;
}
for (i = 0; pathArr[i]; i++)
free(pathArr[i]);
free(pathArr);
free(path);
}
if (!flag)
{
fprintf(stderr, "./hsh: 1: %s: tapilmadi\n", args[0]);
return (127);
}
else
{
if (child_pid == -1)
{
free(fullPath);
perror("fork");
}
else if (child_pid == 0)
{
if (execve(fullPath, args, environ) == -1)
{
free(fullPath);
return (2);
}
}
else
{
waitpid(child_pid, &status, 0);
free(fullPath);
if (WIFEXITED(status))
return (WEXITSTATUS(status));
}
}
return (0);
}