本文主要是介绍Linux 函数之 dup 和 dup2,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、概述:
dup 和 dup2 是复制文件描述符的函数,显而易见,这俩兄弟的前缀是 duplicate 的缩写,即复制;
二、头文件:
#include <unistd.h>
三、函数形式:
int dup(int oldfd);
int dup2(int oldfd, int newfd);
四、功能描述:
(1)dup( ) :生成一个未使用的最小的文件描述符,相当于两个指针指向同一个地址空间(文件);
测试代码:
int main()
{int old_fd, new_fd;old_fd = open("dup.txt", O_RDWR | O_CREAT);printf("old_fd = %d\n", old_fd);new_fd = dup(old_fd);printf("new_fd = %d\n", new_fd);write(old_fd, "old_fd\n", 7);write(new_fd, "new_fd", 6);close(old_fd);close(new_fd);return 0;
}
#输出结果
[root@localhost ~]# ./dup
old_fd = 3
new_fd = 4
#文件内容
old_fd
new_fd
(2)dup2() :dup2 可以自行指定新的文件描述符的值为 newfd,如果newfd已经打开了,则会先关闭newfd,也就是让newfd重定向到了文件oldfd;
测试代码:
int main()
{int oldfd, newfd;oldfd = open("dup2.txt", O_RDWR | O_CREAT);printf("oldfd = %d\n", oldfd);int retfd = dup2(oldfd, STDOUT_FILENO);printf("newfd = %d\n", retfd);write(oldfd, "oldfd\n", 6);write(retfd, "newfd", 5);close(oldfd);close(retfd);return 0;
}
#程序执行结果
[root@localhost ~]# ./dup2
oldfd = 3
#文件内容
newfd = 1
oldfd
newfd
#因为标准输出指向了文件dup2.txt,所以newfd = 1 输出到了文件里
参考文献:
[1] https://blog.csdn.net/qq_29344757/article/details/70764079
[2] https://www.cnblogs.com/fnlingnzb-learner/p/7040726.html
这篇关于Linux 函数之 dup 和 dup2的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!