I'm trying to implement file redirection in my simple shell program. The issue is that when I enter a prompt when I run my shell program to test it (e.g ./test1 > test2 ) instead of executing the command and going onto the next prompt, it sort of lulls and keeps taking in input to redirect to my test2 file. Can't figure out what to do.
for(int i = 1; i < arg_no; i++){
if (strcmp(arg[i], ">") == 0){
fd = open(arg[i+1], O_WRONLY | O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP);
if (fd < 0) {
perror("open");
exit(1);
}
close(STDOUT_FILENO);
if (dup(fd) < 0) {
perror("dup");
exit(1);
}
close(fd);
arg[i] = NULL;
break;
}
else if(strcmp(arg[i], ">&") == 0){
fd = open(arg[i+1], O_WRONLY | O_CREAT, 0644);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);
arg[i] = NULL;
}
else if(strcmp(arg[i], ">>") == 0){
fd = open(arg[i+1], O_WRONLY | O_CREAT | O_APPEND, 0644);
dup2(fd, STDOUT_FILENO);
close(fd);
arg[i] = NULL;
}
else if(strcmp(arg[i] , ">>&") == 0){
fd = open(arg[i+1], O_WRONLY | O_CREAT | O_APPEND, 0644);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);
arg[i] = NULL;
}
else if(strcmp(arg[i], "<") == 0){
fd = open(arg[i+1], O_RDONLY);
dup2(fd, STDIN_FILENO);
close(fd);
arg[i] = NULL;
}
}
My printf statements after dup(fd) don't have any effect, so I'm assuming the program isn't able to close(fd) which is why this is occurring. I'm just not sure why this is or how to force it to close.