6

我在手册页中查找了它,但我仍然不明白...

假设你有dup2(f1,0)。是否使用标准输入切换filedesc.1然后锁定标准输入?

4

1 回答 1

24

dup2不切换文件描述符,它使它们等效。之后dup2(f1, 0),在描述符上打开的任何文件f1现在也在描述符 0 上打开(具有相同的模式和位置​​),即在标准输入上。

如果目标文件描述符(此处为 0)已打开,则dup2调用将其关闭。因此:

before                         after
0: closed, f1: somefile        0: somefile, f1:somefile
0: otherfile, f1: somefile     0: somefile, f1:somefile

不涉及锁定。

dup2当您拥有从标准文件描述符读取或写入的程序的一部分时(除其他外)很有用。例如,假设somefunc()从标准输入读取,但您希望它从另一个文件中读取,而程序的其余部分正在从该文件中获取其标准输入。然后你可以这样做(省略错误检查):

int save_stdin = dup(0);
int somefunc_input_fd = open("input-for-somefunc.data", O_RDONLY);
dup2(somefunc_input_fd, 0);
/* Now the original stdin is open on save_stdin, and input-for-somefunc.data on both somefunc_input_fd and 0. */
somefunc();
close(somefunc_input_fd);
dup2(save_stdin, 0);
close(save_stdin);
于 2014-07-02T19:20:08.360 回答