-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleShell01.c
More file actions
100 lines (93 loc) · 1.97 KB
/
simpleShell01.c
File metadata and controls
100 lines (93 loc) · 1.97 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 "main.h"
#define MAX_INPUT 256
/**
* _getline - gets line from the stdin
*
* Return: string input from buffer
*/
char* _getline(void)
{
char *buffer;
size_t buffSize = MAX_INPUT;
int charCount;
buffer = (char *)malloc(buffSize * sizeof(char));
if (buffer == NULL)
{
perror("Failed to assign buffer ...");
exit(EXIT_FAILURE);
}
printf("#cisfun$ ");
charCount = getline(&buffer, &buffSize, stdin);
if (charCount == -1)
{
if (feof(stdin))
{
kill(getpid(), SIGINT);
}
perror("Failed to get input...");
exit(EXIT_FAILURE);
}
return (buffer);
}
/**
* _tokenize - tokenize the input buffer string
*
* @str: string to tokenize
*
* Return: array of strings
*/
char** _tokenize(char* str)
{
char** argv;
char* token;
int i = 0;
argv = malloc(MAX_INPUT * sizeof(char*));
if (argv == NULL)
{
perror("Failed to allocate memory...");
exit(EXIT_FAILURE);
}
token = strtok(str, " \n");
while (token != NULL)
{
argv[i++] = token;
token = strtok(NULL, " \n");
}
argv[i] = NULL;
return (argv);
}
/**
* main - implementation of simple shell one
*
* Return: Always 0
*/
int main(void)
{
pid_t pid;
char *cmd;
int status;
char **argv;
pid = fork();
while (1)
{
if (pid == 0)
{
cmd = _getline();
argv = _tokenize(cmd);
if (execve(argv[0], argv, NULL) == -1)
{
perror("simple_shell");
exit(EXIT_FAILURE);
}
} else if (pid > 0)
{
wait(&status);
pid = fork();
if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
{
break;
}
}
}
return (0);
}