-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprograms.c
More file actions
107 lines (93 loc) · 2.5 KB
/
programs.c
File metadata and controls
107 lines (93 loc) · 2.5 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
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <linux/limits.h>
#define ALLOCATION_ERROR "fsh: allocation error\n"
//Buffer size for readline function
#define FSH_RL_BUFSIZE 1024
//Buffer size for tokenizing the input and delmiteres for tokenizing
#define FSH_TOK_BUFSIZE 64
#define FSH_TOK_DELIM " \t\r\n\a"
char *fsh_read_line(void)
{
int bufsize = FSH_RL_BUFSIZE;
int position = 0;
char *buffer = malloc(sizeof(char) * bufsize);
int c;
if (!buffer) {
fprintf(stderr, ALLOCATION_ERROR);
exit(EXIT_FAILURE);
}
while (1) {
// Read a character
c = getchar();
// If we hit EOF, replace it with a null character and return.
if (c == EOF || c == '\n') {
buffer[position] = '\0';
return buffer;
}
else {
buffer[position] = c;
}
position++;
// If we have exceeded the buffer, reallocate.
if (position >= bufsize) {
bufsize += FSH_RL_BUFSIZE;
buffer = realloc(buffer, bufsize);
if (!buffer) {
fprintf(stderr, ALLOCATION_ERROR);
exit(EXIT_FAILURE);
}
}
}
}
char **fsh_split_line(char *line)
{
int bufsize = FSH_TOK_BUFSIZE, position = 0;
char **tokens = malloc(bufsize * sizeof(char*));
char *token;
if (!tokens) {
fprintf(stderr, ALLOCATION_ERROR);
exit(EXIT_FAILURE);
}
token = strtok(line, FSH_TOK_DELIM);
while (token != NULL) {
tokens[position] = token;
position++;
if (position >= bufsize) {
bufsize += FSH_TOK_BUFSIZE;
tokens = realloc(tokens, bufsize * sizeof(char*));
if (!tokens) {
fprintf(stderr, ALLOCATION_ERROR);
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, FSH_TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
}
int fsh_launch(char **args)
{
pid_t pid, wpid;
int status;
pid = fork();
if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
perror("fsh");
}
exit(EXIT_FAILURE);
} else if (pid < 0) {
// Error forking
perror("fsh");
} else {
// Parent process
do {
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}