Repository navigation
Expand file tree
/
Copy pathshell.c
More file actions
115 lines (95 loc) · 2.07 KB
/
Copy pathshell.c
File metadata and controls
115 lines (95 loc) · 2.07 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
108
109
110
111
112
113
114
115
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAX_INPUT_SIZE 1024
#define MAX_ARG_COUNT 64
#define DELIM " \t\r\n\a"
/* Function to handle cd and change directory
*/
void handle_cd(char **args) {
if (args[1] == NULL) {
fprintf(stderr, "cd: expected argument\n");
} else {
if (chdir(args[1]) != 0) {
perror("cd");
}
}
}
/* A function to read user's input and return it's value
*/
char *read_input() {
char *input = malloc(MAX_INPUT_SIZE);
if (!input) {
fprintf(stderr, "Memory allocation error\n");
exit(EXIT_FAILURE);
}
printf("> ");
if (fgets(input, MAX_INPUT_SIZE, stdin) == NULL) {
printf("\n");
exit(0);
}
return input;
}
/* A function to process an input, dividing it into commands
* and argument, to return as tokens */
char **parse_input(char *input) {
int bufsize = MAX_ARG_COUNT, position = 0;
char **tokens = malloc(bufsize * sizeof(char *));
char *token;
if (!tokens) {
fprintf(stderr, "Memory allocation error\n");
exit(EXIT_FAILURE);
}
token = strtok(input, DELIM);
while (token != NULL) {
tokens[position++] = token;
token = strtok(NULL, DELIM);
}
tokens[position] = NULL;
return tokens;
}
/* Execute command passed and it's arguments */
void execute_command(char **args) {
if (args[0] == NULL) {
return;
}
if (strcmp(args[0], "cd") == 0) {
handle_cd(args);
return;
}
pid_t pid = fork();
if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
perror("Error executing command");
}
exit(EXIT_FAILURE);
} else if (pid < 0) {
perror("Fork failed");
} else {
// Parent process
int status;
waitpid(pid, &status, 0);
}
}
/* Entry point */
int main() {
char *input;
char **args;
while (1) {
input = read_input();
args = parse_input(input);
// Exit condition
if (args[0] && strcmp(args[0], "exit") == 0) {
free(input);
free(args);
break;
}
execute_command(args);
free(input);
free(args);
}
return 0;
}