-1

I have a question regarding multiple redirections. As what I have for now writes in file1.txt only. I have to implement echo hello > file1.txt > file2.txt > file3.txt on my shell

Here is my code:

int fd1 = open(file1.txt, O_RDWR);
int fd2 = open(file2.txt, O_RDWR);
int fd3 = open(file3, O_RDWR);

dup2(fd1,1);    //to redirect fd1 on the stdout
dup2(fd2,fd1);  //to redirect fd2 to fd1 so i can read from fd1
dup2(fd3,fd1);  //to redirect fd3 to fd1 so i can read from fd1

char* arr = {"hello"};
execvp("echo",arr);

But the code above only works in the first redirection only. The rest which are fd2 and fd3 are not redirected as desired. Appreciate all the help! Thanks

EDIT: The expected results would be that for file1.txt, file2.txt and file3.txt would contain the word "hello".

Cyborg_Trick
  • 174
  • 3
  • 12
  • 1
    What result do you expect from `echo hello > file1.txt > file2.txt > file3.txt`? – choroba Mar 25 '20 at 23:07
  • 1
    `for file1.txt, file2.txt and file3.txt would contain the word "hello".` - but there is only one `hello`, it can go to one file. `dup2` is meant to duplicate _the file descriptor_, not the data. – KamilCuk Mar 25 '20 at 23:11
  • Just added the edit. But basically i expect that file1.txt, file2.txt and file3.txt all contain the word "hello". Thanks! – Cyborg_Trick Mar 25 '20 at 23:11
  • I want to be able to achieve what a normal terminal would do. correct me if i'm wrong but i think if you type this in normal terminal all files would contain "hello" – Cyborg_Trick Mar 25 '20 at 23:13
  • 1
    @PatrickInshutiMakuba Normally, a shell would create/truncate file1.txt, file2.txt and file3.txt but only write anything to file3.txt. The other 2 files would be empty. – William Pursell Mar 26 '20 at 00:21
  • Yes, I made this assumption because i was debugging using macos with zsh. Otherwise, I really get it thanks! – Cyborg_Trick Mar 26 '20 at 00:23

1 Answers1

1

There is no straight forward way to do this in classic Unix process model.

stdout can only point to one location, which is why echo hello > file1.txt > file2.txt > file3.txt will only write to file3.txt in most shells (bash, dash, ksh, busybox sh).

In these shells, you instead have to run:

echo hello | tee file1.txt file2.txt file3.txt > /dev/null

Zsh is the only shell that would write to all three files, and it does it by implementing its own tee just like the above (by setting stdout to a pipe, and forking a process to read from the pipe and write to multiple files). You can do the same.

that other guy
  • 116,971
  • 11
  • 170
  • 194