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.
If you type this into your Linux shell:
Then
test1gets executed withargc == 1and no additional arguments. In particular, the> test2is not passed to your program. The actual shell you are typing at removes these and does the file redirection for you.If your program needs to interpret strings containing
<and>you'll need to enclose them in parentheses, e.g.You'll have to deal with the fact that this parameter is a single string, rather than a series of argv[] pointers.