我在试着理解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

The 2>&1 tells the shell to give the command a file descriptor 2 that is a duplicate of descriptor 1. (i.e stderr & stdout point to same fd).
Now the error message for calling ls on non-existing file and the correct output of ls on existing file show up in tmp1 file.

下面的示例代码在连接标准输入的情况下运行程序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]);
}

子级将读取端复制到文件描述符0上,关闭文件de p中的编剧,以及执行wc.当WC从其标准输入读取时,它从 管道.
这就是管道是如何使用DUP实现的,DUP的一次使用现在您使用PIPE来构建其他东西,这就是系统调用的美妙之处,您使用已有的工具构建一个又一个东西,这些工具又是使用其他东西构建的,依此类推…… 归根结底,系统调用是内核中最基本的工具

干杯:)

C++相关问答推荐

奇怪的print在getchar和getchar跳过后不工作

通过MQTT/蚊子发送大文件—限制在4MB

sizeof结果是否依赖于字符串的声明?

为什么复合文字(C99)的返回会生成更多的汇编代码?

将 typewriter LF打印到Windows终端,而不是隐含的CR+LF

DPDK-DumpCap不捕获端口上的传入数据包

在一个小型玩具项目中实现终端历史记录功能

如何在不使用其他数组或字符串的情况下交换字符串中的两个单词?

ifdef __cplusplus中的整数文字单引号

如何使用唯一数字对整型进行分区

预处理器宏扩展(ISO/IEC 9899:1999(E)§;6.10.3.5示例3)

初始成员、公共初始序列、匿名联合和严格别名如何在C中交互?

如何读取程序中嵌入的数据S自己的ELF?

与外部SPI闪存通信时是否应禁用中断?

在C中,为什么这个带有递增整数的main函数从不因溢出而崩溃?

C中2个数字的加法 - 简单的人类方法

一元运算符

添加/删除链表中的第一个元素

GDB 用内容初始化数组

创建 makefile 来编译位于不同目录中的多个源文件