1

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.

iknn
  • 19
  • 2

1 Answers1

1

If you type this into your Linux shell:

./test1 > test2

Then test1 gets executed with argc == 1 and no additional arguments. In particular, the > test2 is 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.

./test1 "> test2"

You'll have to deal with the fact that this parameter is a single string, rather than a series of argv[] pointers.

pmacfarlane
  • 3,057
  • 1
  • 7
  • 24
  • I don't think OP is dealing with command line arguments. `arg` seems to be a sequence of strings they read from the std input – Ajay Brahmakshatriya Apr 09 '23 at 00:50
  • @AjayBrahmakshatriya In hindsight, I think you are right. I think the question should probably be closed or answered by OP, but I'll leave my answer there until that happens. – pmacfarlane Apr 09 '23 at 07:34