-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlsh.c
365 lines (314 loc) · 7.74 KB
/
lsh.c
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*
* Main source code file for lsh shell program
*
* You are free to add functions to this file.
* If you want to add functions in a separate file
* you will need to modify Makefile to compile
* your additional functions.
*
* Add appropriate comments in your code to make it
* easier for us while grading your assignment.
*
* Submit the entire lab1 folder as a tar archive (.tgz).
* Command to create submission archive:
$> tar cvf lab1.tgz lab1/
*
* All the best
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include "parse.h"
#define PERM S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
/*
* Function declarations
*/
void PrintCommand(int, Command *);
void PrintPgm(Pgm *);
void stripwhite(char *);
pid_t wait(int *wstatus);
pid_t fork(void);
int setpgid(pid_t pid, pid_t pgid);
void executePgm(Pgm *pgm);
void eexit(char *description);
void setupExecEnv(Command *cmd);
void SIGCHLD_handler(int signo);
void SIGINT_handler(int signo);
/* When non-zero, this global means the user is done using this program. */
int done = 0;
/* The pid of the process running in foreground. */
pid_t foreground_pid = 0;
/*
* Name: main
*
* Description: Gets the ball rolling...
*
*/
int main(void)
{
Command cmd;
int n;
while (!done) {
char *line;
/* Register singal handlers */
signal(SIGCHLD, SIGCHLD_handler);
signal(SIGINT, SIGINT_handler);
line = readline("> ");
if (!line) {
/* Encountered EOF at top level */
done = 1;
}
else {
/*
* Remove leading and trailing whitespace from the line
* Then, if there is anything left, add it to the history list
* and execute it.
*/
stripwhite(line);
if(*line) {
add_history(line);
n = parse(line, &cmd);
if (n == 1) {
/* Parse cmd successfully */
/* Handle the cd command */
if (!strcmp((cmd.pgm) -> pgmlist[0], "cd") && !((cmd.pgm) -> next)) {
char *to = (cmd.pgm) -> pgmlist[1];
if (!to)
to = getenv("HOME");
if (chdir(to) == -1)
perror("chdir error: ");
continue;
}
/* Handle the exit command */
if (!strcmp((cmd.pgm) -> pgmlist[0], "exit")&& !((cmd.pgm) -> next))
exit(0);
pid_t pid = fork();
if (pid < 0) {
eexit("Error when forking.\n");
} else if (pid == 0) {
/* In child process */
/* Setup executing environment */
setupExecEnv(&cmd);
/* Start executing program list */
executePgm(cmd.pgm);
} else {
/* In parent process */
int status;
/* Record the child process's pid, in case we want to kill it */
foreground_pid = pid;
if (!cmd.bakground && wait(&status) == -1) {
/* Wait for child process to finish and clean up.
* For background process, leave it to signal_handler.
*/
eexit("Error when waiting for child process to complete.\n");
}
/* Nothing in foreground now */
foreground_pid = 0;
}
} else {
printf("Parsing cmd failed.\n");
}
}
}
if(line) {
free(line);
}
}
return 0;
}
/*
* Name: setupExecEnv
*
* Description: Setup Execution Environment. Including wether or not runing in
* background and redirection.
*
*/
void setupExecEnv(Command *cmd)
{
if (cmd -> bakground) {
/* Run command in background */
setpgid(0, 0);
}
if (cmd -> rstdin) {
/* Redirect stdin to file */
int infd;
if ((infd = open(cmd -> rstdin, O_RDONLY)) < 0)
eexit("open file error.\n");
if (infd != STDIN_FILENO)
if (dup2(infd, STDIN_FILENO) != STDIN_FILENO)
eexit("dup2 error.\n");
close(infd);
}
if (cmd -> rstdout) {
/* Redirect stdout to file */
int outfd;
if ((outfd = open(cmd -> rstdout, O_CREAT | O_WRONLY | O_TRUNC, PERM)) < 0)
eexit("open file error.\n");
if (outfd != STDOUT_FILENO)
if (dup2(outfd, STDOUT_FILENO) != STDOUT_FILENO)
eexit("dup2 error.\n");
close(outfd);
}
}
/*
* Name: executePgm
*
* Description: Execute all the commands that are in Pgm linked list. Every
* command is run as the child process of the previous command in the linked list.
*
*/
void executePgm(Pgm *pgm) {
if (pgm == NULL) return;
if (pgm -> next) {
/* Has more command */
int pipefd[2], status;
pid_t pid;
if (pipe(pipefd) == -1)
eexit("Fail to create pipe.\n");
pid = fork();
if (pid < 0) {
eexit("Fail to create child process when executing command.\n");
} else if (pid == 0) {
/* In child process, write end of the pipe */
close(pipefd[0]);
if (pipefd[1] != STDOUT_FILENO) {
if (dup2(pipefd[1], STDOUT_FILENO) != STDOUT_FILENO)
eexit("dup2 error.\n");
close(pipefd[1]);
}
/* Call executePgm recursively */
executePgm(pgm -> next);
} else {
/* In parent process, read end of the pipe */
close(pipefd[1]);
/* Bind stdin to the read end of the pipe */
if (pipefd[0] != STDIN_FILENO) {
if (dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO)
eexit("dup2 error.\n");
close(pipefd[0]);
}
/* Wait for the child process to finish */
wait(&status);
/* Execute the expected program after child finish*/
execvp(pgm->pgmlist[0], pgm->pgmlist);
perror("lsh error");
exit(-1);
}
} else {
/* No more command */
execvp(pgm->pgmlist[0], pgm->pgmlist);
perror("lsh error");
exit(-1);
}
}
/*
* Name: eexit
*
* Description: Print error message and exit with code -1.
*
*/
void eexit(char *description)
{
perror(description);
exit(-1);
}
/*
* Name: SIGCHLD_handler
*
* Description: Handle the SIGCHLD signal and clean up the zombies
*
*/
void SIGCHLD_handler(int signo)
{
if (signo == SIGCHLD) {
int status;
pid_t pid;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
printf("Process PID=%d now terminated.\n", pid);
}
}
}
/*
* Name: SIGINT_handler
*
* Description: Handle the SIGINT signal and terminate foreground running
* process.
*
*/
void SIGINT_handler(int signo)
{
if (signo == SIGINT && foreground_pid > 0) {
if ((kill(foreground_pid, SIGTERM)) == -1)
eexit("Error when terminating foreground process.\n");
else
foreground_pid = 0;
}
}
/*
* Name: PrintCommand
*
* Description: Prints a Command structure as returned by parse on stdout.
*
*/
void
PrintCommand (int n, Command *cmd)
{
printf("Parse returned %d:\n", n);
printf(" stdin : %s\n", cmd->rstdin ? cmd->rstdin : "<none>" );
printf(" stdout: %s\n", cmd->rstdout ? cmd->rstdout : "<none>" );
printf(" bg : %s\n", cmd->bakground ? "yes" : "no");
PrintPgm(cmd->pgm);
}
/*
* Name: PrintPgm
*
* Description: Prints a list of Pgm:s
*
*/
void
PrintPgm (Pgm *p)
{
if (p == NULL) {
return;
}
else {
char **pl = p->pgmlist;
/* The list is in reversed order so print
* it reversed to get right
*/
PrintPgm(p->next);
printf(" [");
while (*pl) {
printf("%s ", *pl++);
}
printf("]\n");
}
}
/*
* Name: stripwhite
*
* Description: Strip whitespace from the start and end of STRING.
*/
void
stripwhite (char *string)
{
register int i = 0;
while (isspace( string[i] )) {
i++;
}
if (i) {
strcpy (string, string + i);
}
i = strlen( string ) - 1;
while (i> 0 && isspace (string[i])) {
i--;
}
string [++i] = '\0';
}