2

I am making a shell (works well). However, right now I am trying in implement output redirection. cat test1.txt > text2.txt. If I run commands without redirection, it works perfectly. So what am I missing in my redirection output code?

Text1.txt

This is some dummy text

It I ran my shell right now, it would be as follows

$shell cat test1.txt > text2.txt
Executing cat
Everything went well!
$shell

Now, if I open text2.txt. This is what it contains

Executing cat
This is some dummy text

Everything went well!

My redirection code

char **mycommand = {"cat", "text1.txt", ">", "text2.txt"};
if (strcmp(mycommand[2], ">") == 0) {
   int fd = open(mycommand[3], O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
   dup2(fd, STDOUT);
   mycommand[2] = '\0';
   break;
}
// Then it does all the execution stuff on mycommand
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Paul
  • 127
  • 1
  • 1
  • 7
  • " Then it does all the execution stuff on mycommand" -- and where is that redirection stuff ? IMHO your question needs more details, more code may be – asio_guy Oct 07 '18 at 03:09
  • 3
    If I understand you correctly, you're saying that in addition to the output of the command your shell runs (`cat` in the example), your shell also produces its own output, and this additional output is *both* displayed on the screen and written into the file. The redirection code you present is not responsible for any such duplication of the output. This sort of thing is why we generally ask for a [mcve]. – John Bollinger Oct 07 '18 at 03:31
  • 1
    You should only call `dup2()` in the child process that you fork to execute the command. If the shell prints any messages itself, that should be in the parent process. – Barmar Oct 07 '18 at 04:17
  • Don't forget to close the original file descriptor after duplicating to one of the standard I/O streams. Also, don't forget that `O_TRUNC` is necessary to truncate a file (but the new writing will overwrite from the beginning of the file if you don't specify `O_APPEND`). It isn't clear that the absence of `O_TRUNC` is the cause of your problem. (Also, why `O_RDWR` instead of `O_WRONLY`?) – Jonathan Leffler Oct 07 '18 at 17:41
  • You might also note than in a standard shell, someone could write ` text2.txt cat` and the I/O redirections are valid (input from `text1.txt`, output to `text2.txt`) and the command is essentially equivalent to your original — it's different because the shell opens `text1.txt` instead of `cat` doing so. You probably don't have to worry about this yet, but `cat text1.txt > text2.txt text3.txt` is also legitimate, and places the content of `text1.txt` and `text3.txt` into `text2.txt`. You code would ignore the extra non-redirection argument, `text3.txt`. – Jonathan Leffler Oct 07 '18 at 17:45

0 Answers0