-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_shell.c
More file actions
100 lines (85 loc) · 1.57 KB
/
Copy pathsimple_shell.c
File metadata and controls
100 lines (85 loc) · 1.57 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
#include "shell.h"
/**
* displayPrompt - Display the shell prompt
*
* Return: no return
*/
void displayPrompt(void)
{
if (isatty(STDIN_FILENO))
write(STDOUT_FILENO, "$ ", 3);
}
/**
* executeCommand - executes commands
*
* @inputBuffer: user input
* @env: environment variable
*
* Return: no return
*/
void executeCommand(char *inputBuffer, char **env)
{
pid_t childPid;
int childStatus;
char *token;
char **tokenArray;
int i = 0;
/* Create a child process */
childPid = fork();
if (childPid == -1)
{
perror("child creation failed.");
exit(EXIT_FAILURE);
}
token = strtok(inputBuffer, " ");
tokenArray = malloc(sizeof(char *) * 1024);
for (i = 0; token; i++)
{
tokenArray[i] = token;
token = strtok(NULL, " \n");
}
tokenArray[i] = NULL;
if (childPid == 0)
{
if (execve(tokenArray[0], tokenArray, env) == -1)
{
perror("./shell");
exit(1);
}
}
else
{
wait(&childStatus);
free(tokenArray);
}
}
/**
* main - Main entry point of our program
* @argc: Argument count
* @argv: Array of argument values pointer
* @env: NULL terminated array of strings
* Return: O Always success
*/
int main(int argc, char **argv, char **env)
{
char *inputBuffer = NULL;
size_t bufferSize = 0;
ssize_t bytesRead;
(void)argc;
(void)argv;
while (1)
{
displayPrompt();
bytesRead = getline(&inputBuffer, &bufferSize, stdin);
if (bytesRead == -1)
{
free(inputBuffer);
exit(1);
}
if (inputBuffer[bytesRead - 1] == '\n')
inputBuffer[bytesRead - 1] = '\0';
executeCommand(inputBuffer, env);
}
free(inputBuffer);
return (0);
}