Reputation: 185
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".
Upvotes: 0
Views: 1116
Reputation: 123650
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.
Upvotes: 2