dup()和dup2()Linux系统调用

dup()

null

dup()系统调用创建文件描述符的副本。

  • 它使用编号最低的未使用描述符作为新描述符。
  • 如果成功创建了副本,则原始和副本文件描述符可以互换使用。
  • 它们都引用相同的打开文件描述,因此共享文件偏移量和文件状态标志。

语法:

int dup(int oldfd);
oldfd: old file descriptor whose copy is to be created.

// CPP program to illustrate dup()
#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
// open() returns a file descriptor file_desc to a
// the file "dup.txt" here"
int file_desc = open( "dup.txt" , O_WRONLY | O_APPEND);
if (file_desc < 0)
printf ( "Error opening the file" );
// dup() will create the copy of file_desc as the copy_desc
// then both can be used interchangeably.
int copy_desc = dup(file_desc);
// write() will write the given string into the file
// referred by the file descriptors
write(copy_desc, "This will be output to the file named dup.txt" , 46);
write(file_desc, "This will also be output to the file named dup.txt" , 51);
return 0;
}


请注意,此程序不会在联机编译器中运行,因为它包括打开文件并在其上写入。

说明: open()将文件描述符file_desc返回给名为“dup.txt”的文件。file_desc可用于对文件“dup.txt”执行一些文件操作。在使用dup()系统调用后,将创建文件_desc的副本copy _desc。该副本还可用于对同一文件“dup.txt”执行某些文件操作。经过两次写入操作,一次是使用file_desc,另一次是使用copy_desc,编辑相同的文件,即“dup.txt”。

在运行代码之前,让写操作之前的文件“dup.txt”如下所示: 图片[1]-dup()和dup2()Linux系统调用-yiteyi-C++库

运行上述C程序后,文件“dup.txt”如下所示: 图片[2]-dup()和dup2()Linux系统调用-yiteyi-C++库

dup2()

dup2()系统调用与dup()类似,但它们之间的基本区别在于,它不使用编号最低的未使用文件描述符,而是使用用户指定的描述符编号。 语法:

int dup2(int oldfd, int newfd);
oldfd: old file descriptor
newfd new file descriptor which is used by dup2() to create a copy.

要点:

  • 包括头文件unistd。h用于使用dup()和dup2()系统调用。
  • 如果描述符newfd以前是打开的,则在重新使用之前会自动关闭它。
  • 如果oldfd不是有效的文件描述符,则调用失败,newfd未关闭。
  • 如果oldfd是一个有效的文件描述符,并且newfd与oldfd具有相同的值,则dup2()会 没有,返回newfd。

dup2()系统调用的巧妙用法: 与dup2()一样,可以放置任何文件描述符来代替newfd。下面是一个C实现,其中使用了标准输出的文件描述符(stdout)。这将导致所有printf()语句都写入旧文件描述符引用的文件中。

// CPP program to illustrate dup2()
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
int main()
{
int file_desc = open( "tricky.txt" ,O_WRONLY | O_APPEND);
// here the newfd is the file descriptor of stdout (i.e. 1)
dup2(file_desc, 1) ;
// All the printf statements will be written in the file
// "tricky.txt"
printf ( "I will be printed in the file tricky.txt" );
return 0;
}


如下图所示: 让dup2()操作之前的文件“tricky.txt”如下所示: 图片[3]-dup()和dup2()Linux系统调用-yiteyi-C++库

运行上述C程序后,文件“tricky.txt”如下所示: 图片[4]-dup()和dup2()Linux系统调用-yiteyi-C++库

参考: dup(2)–Linux手册页

本文由 马扎尔·伊玛目·汗 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享