-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrsh.c
More file actions
128 lines (102 loc) · 2.48 KB
/
rsh.c
File metadata and controls
128 lines (102 loc) · 2.48 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
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <stdio.h>
#include <stdlib.h>
#include <spawn.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#define N 12
extern char **environ;
char *allowed[N] = {"cp", "touch", "mkdir", "ls", "pwd", "cat",
"grep", "chmod", "diff", "cd", "exit", "help"};
int isAllowed(const char* cmd) {
for(int i = 0; i < N; i++) {
if(strcmp(cmd, allowed[i]) == 0) return 1;
}
printf("NOT ALLOWED!\n");
return 0;
}
int spawnProcess(char* const* argv) {
pid_t pid;
int status;
posix_spawnattr_t attr;
// Initialize spawn attributes
posix_spawnattr_init(&attr);
// Set flags if needed, for example, to specify the scheduling policy
// posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSCHEDULER);
// Spawn a new process
if (posix_spawnp(&pid, argv[0], NULL, &attr, argv, environ) != 0) {
perror("spawn failed");
exit(EXIT_FAILURE);
}
// Wait for the spawned process to terminate
if (waitpid(pid, &status, 0) == -1) {
perror("waitpid failed");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
// printf("Spawned process exited with status %d\n", WEXITSTATUS(status));
}
// Destroy spawn attributes
posix_spawnattr_destroy(&attr);
return EXIT_SUCCESS;
}
int main() {
char line[256];
while (1) {
fprintf(stderr, "rsh>");
if (fgets(line, 256, stdin)==NULL) continue;
if (strcmp(line, "\n") == 0) continue;
line[strlen(line)-1] = '\0';
char* argv[20] = {NULL};
// Parse input command
int i = 0;
char* token = strtok(line, " ");
while (token != NULL && i < 20) {
argv[i] = token;
i++;
token = strtok(NULL, " ");
}
if (isAllowed(argv[0]) == 0) continue;
// printf("{");
// for(i = 0; i < 19; i++) {
// printf("\"%s\",",argv[i]);
// }
// printf("\"%s\"}\n", argv[19]);
// Spawn processes for the first 9 commands
for(int i = 0; i < 9; i++) {
if(strcmp(argv[0], allowed[i]) == 0) {
spawnProcess(argv);
break;
}
}
// cd
if(strcmp(argv[0], "cd") == 0) {
if(argv[2] != NULL) {
printf("-rsh: cd: too many arguments\n");
continue;
}
chdir(argv[1]);
}
// exit
if(strcmp(argv[0], "exit") == 0) {
return 0;
}
// help
if(strcmp(argv[0], "help") == 0) {
printf("The allowed commands are:\n"
"1: cp\n"
"2: touch\n"
"3: mkdir\n"
"4: ls\n"
"5: pwd\n"
"6: cat\n"
"7: grep\n"
"8: chmod\n"
"9: diff\n"
"10: cd\n"
"11: exit\n"
"12: help\n");
}
}
return 0;
}