82 lines
1.7 KiB
C
82 lines
1.7 KiB
C
#include"include/redirection.h"
|
|
#include<string.h>
|
|
#include<fcntl.h>
|
|
#include<unistd.h>
|
|
#include<sys/wait.h>
|
|
#include<signal.h>
|
|
#include<stdio.h>
|
|
#include<stdlib.h>
|
|
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);
|
|
}
|
|
}
|
|
}
|