c - dup2/dup - 为什么我需要复制文件描述符?

我正在尝试了解 dup2dup 的用法。

来自手册页:

DESCRIPTION

dup and dup2 create a copy of the file descriptor oldfd.
After successful return of dup or dup2, the old and new descriptors may
be used interchangeably. They share locks, file position pointers and
flags; for example, if the file position is modified by using lseek on
one of the descriptors, the position is also changed for the other.

The two descriptors do not share the close-on-exec flag, however.

dup uses the lowest-numbered unused descriptor for the new descriptor.

dup2 makes newfd be the copy of oldfd, closing newfd first if necessary.  

RETURN VALUE

dup and dup2 return the new descriptor, or -1 if an error occurred 
(in which case, errno is set appropriately).  

为什么我需要那个系统调用?复制文件描述符有什么用?

如果我有文件描述符,为什么要复制它?

如果您能解释一下并给我一个需要 dup2/dup 的示例,我将不胜感激。

谢谢

最佳答案

dup 系统调用复制一个现有的文件描述符,返回一个新的 指的是相同的底层 I/O 对象。

Dup 允许 shell 执行如下命令:

ls existing-file non-existing-file > tmp1  2>&1

2>&1 告诉 shell 给命令一个文件描述符 2,它是描述符 1 的副本。(即 stderr 和 stdout 指向同一个 fd)。
现在在 non-existing file 上调用 ls 的错误消息和 existing filels 的正确输出显示在 tmp1 文件中。

以下示例代码在连接标准输入的情况下运行程序 wc 到管道的读取端。

int p[2];
char *argv[2];
argv[0] = "wc";
argv[1] = 0;
pipe(p);
if(fork() == 0) {
    close(STDIN); //CHILD CLOSING stdin
    dup(p[STDIN]); // copies the fd of read end of pipe into its fd i.e 0 (STDIN)
    close(p[STDIN]);
    close(p[STDOUT]);
    exec("/bin/wc", argv);
} else {
    write(p[STDOUT], "hello world\n", 12);
    close(p[STDIN]);
    close(p[STDOUT]);
}

child 将读取端复制到文件描述符0上,关闭文件de p 中的脚本和 wc 中的 execs。当 wc 从其标准输入中读取时,它从 管道。
这就是使用 dup 实现管道的方式,现在使用 dup 的一种用途是使用管道构建其他东西,这就是系统调用的美妙之处,您使用已经存在的工具构建一个又一个的东西,这些工具又是使用构建的别的东西等等.. 最后,系统调用是您在内核中获得的最基本的工具

干杯:)

https://stackoverflow.com/questions/11635219/

相关文章:

c - 如何在linux c程序中获取pthread的线程ID?

python - 在几个文件中拆分views.py

python - 打印 Python 类的所有属性

python - os.path.dirname(__file__) 返回空

linux - shell脚本杀死监听端口3000的进程?

linux - Unix:如何删除文件中列出的文件

python - 如何为子图设置 xlim 和 ylim

python - 在 IPython 中自动重新加载模块

linux - 如何 RSYNC 单个文件?

python - 如何在 Python 中进行 scp?