如何在C中正确执行多重重定向



我有一个关于多个重定向的问题。因为我现在只在file1.text中写。我必须在我的shell 上实现echo hello > file1.txt > file2.txt > file3.txt

这是我的代码:

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);

但是上面的代码只适用于第一次重定向。其余的fd2和fd3没有按需要重定向。感谢所有的帮助!感谢

编辑:对于file1.txtfile2.txt件3.txt预期结果将包含单词"hello"。

在经典的Unix进程模型中,没有直接的方法可以做到这一点。

stdout只能指向一个位置,这就是为什么echo hello > file1.txt > file2.txt > file3.txt在大多数shell(bash、dash、ksh、busybox-sh(中只写入file3.txt的原因。

在这些shell中,您必须运行:

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

Zsh是唯一一个可以写入所有三个文件的shell,它通过实现自己的tee来实现这一点,就像上面一样(通过将stdout设置为管道,并分叉一个进程从管道读取并写入多个文件(。你也可以这么做。

最新更新