-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshell.c
140 lines (132 loc) · 2.54 KB
/
shell.c
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include "main.h"
void free_argv_array(char **argv);
char *search_path(const char *command);
/**
* main - entry point
*
* Return: 0 if successful or non-zero if not
*/
int main(void)
{
pid_t child_pid;
char **argv, *buffer, *token, *path;
int status;
while (1)
{
buffer = _getline();
token = strtok(buffer, "\n");
while (token != NULL)
{
argv = _argv_array(token);
if (argv[0] == NULL || strchr(argv[0], ' ') != NULL)
{
free(buffer);
free_argv_array(argv);
break;
}
if (strchr(argv[0], '/') == NULL)
{
if (strcmp(argv[0], "env") == 0)
{
_print_env();
free(buffer);
free_argv_array(argv);
break;
}
else if (strcmp(argv[0], "exit") == 0)
{
free(buffer);
free_argv_array(argv);
exit(0);
}
path = search_path(argv[0]);
if (path != NULL)
{
free(argv[0]);
argv[0] = path;
}
else
{
fprintf(stderr, "./hsh: 1: %s: not found\n", token);
free(buffer);
free_argv_array(argv);
break;
}
token = strtok(NULL, "\n");
}
child_pid = fork();
if (child_pid == 0)
{
if (execve(argv[0], argv, NULL) == -1)
{
free(buffer);
free_argv_array(argv);
exit(1);
}
}
if (child_pid != 0)
{
waitpid(child_pid, &status, 0);
if (WIFEXITED(status))
{
if (!isatty(STDIN_FILENO) || WEXITSTATUS(status) == 0)
{
free(buffer);
free_argv_array(argv);
break;
}
}
}
}
}
return (0);
}
/**
* free_argv_array - free array
* @argv: array to be freed of memory
*
* Return: nothing
*/
void free_argv_array(char **argv)
{
int i = 0;
while (argv[i] != NULL)
{
free(argv[i]);
i++;
}
free(argv);
}
/**
* search_path - get the path for the command
* @command: command input
*
* Return: new string containing full path
*/
char *search_path(const char *command)
{
char *full_path;
char *path_env = getenv("PATH");
/* Duplicate the PATH string to avoid modifying the original */
char *dir = strtok(strdup(path_env), ":");
while (dir != NULL)
{
/* Build full path by concatenating the directory and the command */
/* +2 for '/' and '\0' */
full_path = malloc(strlen(dir) + strlen(command) + 2);
if (full_path == NULL)
{
perror("Memory allocation error");
exit(EXIT_FAILURE);
}
sprintf(full_path, "%s/%s", dir, command);
/* Check if the file at the constructed path exists and is executable */
if (access(full_path, X_OK) == 0)
{
return (full_path);
}
free(full_path);
dir = strtok(NULL, ":");
}
return (NULL);
}