diff --git a/usr/src/sh.c b/usr/src/sh.c index 4d4dccf459..41b77314a6 100644 --- a/usr/src/sh.c +++ b/usr/src/sh.c @@ -28,12 +28,14 @@ #include #include #include +#include #define TOKEN_NR 10 #define ARGS_MAX 16 char tokens[TOKEN_NR][80]; char prompt[] = "so3% "; +char file_buff[500]; void parse_token(char *str) { int i = 0; @@ -53,10 +55,10 @@ void parse_token(char *str) { * Process the command with the different tokens */ void process_cmd(void) { - int i, pid_child, background, arg_pos, arg_pos2; + int i, pid_child, background, arg_pos, arg_pos2, redirection, byte_read; char *argv[ARGS_MAX], *argv2[ARGS_MAX]; char filename[30]; - int pid, sig, pid_child2; + int pid, sig, pid_child2, fd; int pipe_on = 0; int pipe_fd[2]; @@ -133,6 +135,7 @@ void process_cmd(void) { arg_pos = 0; arg_pos2 = 0; background = 0; + redirection = 0; while (!background && tokens[arg_pos][0] != 0) { /* Check for & */ if (!strcmp(tokens[arg_pos], "&")) @@ -141,10 +144,15 @@ void process_cmd(void) { if (!strcmp(tokens[arg_pos], "|")) { pipe_on = 1; argv[arg_pos] = NULL; + } else if (!strcmp(tokens[arg_pos], ">")) { + redirection = 1; + argv[arg_pos] = NULL; } else { if (pipe_on) { argv2[arg_pos2] = tokens[arg_pos]; arg_pos2++; + } else if (redirection) { + argv2[0] = tokens[arg_pos]; } else argv[arg_pos] = tokens[arg_pos]; } @@ -179,8 +187,7 @@ void process_cmd(void) { exit(-1); } - } - else { + } else { close(pipe_fd[1]); dup2(pipe_fd[0], STDIN_FILENO); @@ -194,6 +201,34 @@ void process_cmd(void) { } } + } else if (redirection) { + fd = open(argv2[0], O_WRONLY | O_CREAT); + if (fd < 0) { + printf("Error opening/creating output file...\n"); + return; + } + + pipe(pipe_fd); + pid_child2 = fork(); + if (!pid_child2) { + close(pipe_fd[0]); + dup2(pipe_fd[1], STDOUT_FILENO); + strcpy(filename, argv[0]); + strcat(filename, ".elf"); + + if (execv(filename, argv) == -1) { + printf("%s: exec failed.\n", argv[0]); + exit(-1); + } + + } else { + close(pipe_fd[1]); + while ((byte_readen = read(pipe_fd[0], file_buff, 500)) > 0) { + write(fd, file_buff, byte_readen); + } + close(fd); + } + } else { strcpy(filename, tokens[0]); argv[0] = tokens[0]; @@ -258,7 +293,6 @@ void main(int argc, char *argv[]) /* Check if there is at least one token to be processed */ if (tokens[0][0] != 0) process_cmd(); - - + } }