diff --git a/include/redirection.h b/include/redirection.h new file mode 100644 index 0000000..5f5e931 --- /dev/null +++ b/include/redirection.h @@ -0,0 +1,8 @@ +#ifndef REDIRECTION_H +#define REDIRECTION_H + + +int detectRedirect(char **args, char **filename); +void executeRedirect(char **args, int type, char *filename); + +#endif diff --git a/main.c b/main.c index 4454d80..6d7893f 100644 --- a/main.c +++ b/main.c @@ -6,6 +6,7 @@ #include #include #include +#include"include/redirection.h" pid_t backgroundPids[64]; int backgroundCount = 0; void handleSIGINT(int sig) { @@ -112,6 +113,14 @@ int main() { free(parsed); continue; } + char *filename; + int redirectionType = detectRedirect(parsed, &filename); + if (redirectionType) { + executeRedirect(parsed, redirectionType, filename); + free(parsed); + free(line); + continue; + } pid_t pid = fork(); if(pid == 0) { signal(SIGINT, SIG_DFL); diff --git a/makefile b/makefile index e64d1f2..17f1d89 100644 --- a/makefile +++ b/makefile @@ -2,8 +2,8 @@ CC = gcc CFLAGS = -Wall LIBS = -lreadline -tinysh: main.c - $(CC) $(CFLAGS) main.c -o tinysh $(LIBS) +tinysh: main.c redirection.c + $(CC) $(CFLAGS) main.c redirection.c -o tinysh $(LIBS) clean: rm -f tinysh diff --git a/redirection.c b/redirection.c new file mode 100644 index 0000000..3e143aa --- /dev/null +++ b/redirection.c @@ -0,0 +1,81 @@ +#include"include/redirection.h" +#include +#include +#include +#include +#include +#include +#include +int detectRedirect(char **args, char **filename) { + for(int i = 0; args[i] != NULL; i++) { + if(strcmp(args[i], "<") == 0) { + *filename = args[i + 1]; + args[i] = NULL; + args[i + 1] = NULL; + return 3; + } + if(strcmp(args[i], ">") == 0) { + *filename = args[i + 1]; + args[i] = NULL; + args[i + 1] = NULL; + return 1; + } + if(strcmp(args[i], ">>") == 0) { + *filename = args[i + 1]; + args[i] = NULL; + args [i + 1] = NULL; + return 2; + } + } + return 0; +} +void executeRedirect(char **args, int type, char *filename) { + if (type == 1) { + int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); + pid_t pid = fork(); + if(pid == 0) { + dup2(fd, STDOUT_FILENO); + close(fd); + signal(SIGINT, SIG_DFL); + execvp(args[0], args); + perror("tinysh"); + exit(1); + } + else if(pid > 0) { + close(fd); + wait(NULL); + } + } + if (type == 2) { + int fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, 0644); + pid_t pid = fork(); + if(pid == 0) { + dup2(fd, STDOUT_FILENO); + close(fd); + signal(SIGINT, SIG_DFL); + execvp(args[0], args); + perror("tinysh"); + exit(1); + } + if (pid > 0) { + close(fd); + wait(NULL); + } + } + if (type == 3) { + int fd = open(filename, O_RDONLY); + pid_t pid = fork(); + if (pid == 0) { + dup2(fd, STDIN_FILENO); + close(fd); + signal(SIGINT, SIG_DFL); + execvp(args[0], args); + perror("tinysh"); + exit(1); + } + else if (pid > 0) { + close(fd); + wait(NULL); + } + } +}