【问题标题】:What does dup2() do in Cdup2() 在 C 中做了什么
【发布时间】:2023-03-20 05:07:01
【问题描述】:

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

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

【问题讨论】:

  • 这和bash有什么关系?
  • Unix,管道,我很抱歉
  • "dup2() 使newfd成为oldfd的副本,必要时先关闭newfd"
  • int dup2(int oldfd, int newfd);

标签: c pipe file-descriptor dup2


【解决方案1】:

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

【讨论】:

  • 彻底的解释,tnx
猜你喜欢
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 2010-09-19
  • 2010-12-28
  • 1970-01-01
相关资源
最近更新 更多