dup函数简介
dup()和dup2()函数都可以用来复制一个文件描述符,其原型为
int dup(int oldfd);
int dup2(int oldfd,int newfd);
dup函数创建一个新的文件描述符,该新文件描述符和原文件描述符指向相同的文件、管道、或网络连接,dup返回的新文件描述符是取系统当前可用的最小整数值(一般情况下系统默认了标准输入0、标准输出1、标准出错2,在没有其他文件描述符的情况下,文件描述符fd的值为3,那么首次调用dup函数的返回值为4(3+1))
dup2函数和dup类似,他返回的值为第一个不小于新文件描述符newfd的整数值
dup和dup2调用失败时都返回-1并设置errno
dup函数示例
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
int main()
{
int oldfd = open("wyg.txt",O_RDWR | O_CREAT,664);//第一次打开文件,返回的文件描述符(oldfd)值为3
if(oldfd < 0)
{
perror("open");
}
printf("oldfd is : %d\n",oldfd);
int newfd = dup(oldfd);//调用dup函数,返回的新文件描述符为可用的最小正整数,即为4
if(newfd < 0)//判断函数是否调用正确,newfd的值为-1时调用失败
{
perror("dup");
}
printf("newfd is : %d\n",newfd);
char *data = "this is new data";
write(newfd,data,strlen(data));
return 0;
}
由程序可以看出,oldfd文件描述符为3,newfd文件描述符为4,而因为调用了dup函数,oldfd和newfd都可以对wyg.txt进行操作。
可以理解为:oldfd句柄指向wyg.txt的文件结构体,dup()指向完毕后,newfd句柄也会指向wyg.txt文件描述结构体。所以对newfd句柄所指的文件操作,等价于操作wyg.txt文件。
dup2()与dup()的区别在于可以用newfd来指定新描述符的值,若newfd所指向的文件已打开,会先将其关闭;若newfd等于oldfd就不关闭newfd,newfd和oldfd共同指向一份文件
dup2函数示例
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
int main()
{
int oldfd = open("wyg.txt",O_RDWR | O_CREAT,664);
if(oldfd < 0)
{
perror("open");
}
printf("oldfd is : %d\n",oldfd);
int newfd = dup2(oldfd , 1);
if(newfd < 0)
{
perror("dup");
}
printf("this is new data,newfd:%d\n",newfd);
return 0;
}
在该程序中,dup2函数创建新的指向xyg.txt文件的文件描述符为1,即wyg.txt文件的描述符为标准输出描述符,此时本来打印到终端的字符串就打印到了wyg.txt文件中了。这也是Linux操作系统的重定向实现方法。