#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
作用:dup函数实现对一个文件的文件描述符进行复制,复制之后该进程就会新增加一一个文件描述符指向该文件(即实现同一个文件对应多个文件描述符)。dup2函数:如果new是一个被打开的文件描述符(与old不是同一个文件),则在拷贝前先关闭new(new就不需要占据那个文件描述符了),即使new文件的文件描述符重新指向old文件;如果两个文件描述符对应的是同一个文件,则直接返回文件描述符。 文件描述符的复制又称为文件描述符的重定向。
dup返回值:返回新的文件描述符(文件描述符表中最小的未被占用的文件描述符)。 出错,返回-1。
dup2返回值:如果两个文件描述符对应的是同一个文件,则直接返回文件描述符。(不拷贝)。如果不是同一个文件,则返回new的那个文件描述符。出错 返回-1。
//dup函数代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>int main()
{int fd = open("a.txt", O_RDWR); //文件第一次被打开时,其文件指针置于文件首部if(fd == -1){perror("open");exit(1);}printf("file open fd = %d\n", fd);int ret = dup(fd); //文件描述符的复制(重定向)if(ret == -1){perror("dup");exit(1);}printf("dup fd = %d\n", ret);char* buf = "你是猴子派来的救兵吗????\n";char* buf1 = "你大爷的,我是程序猿!!!\n";write(fd, buf, strlen(buf)); //通过fd来向文件写入数据write(ret, buf1, strlen(buf1)); //通过ret来向同一文件继续写入数据,注意是追加写入,因为一个文件的文件读写指针只有一个,因此第一个文件操作后,第二个接着第一个的位置继续进行。close(fd); //此时只是释放了fd,但还是可以通过ret来使用该文件。close(ret); //释放retreturn 0;
}//dup2函数代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>int main( )
{int fd = open("english.txt", O_RDWR);if(fd == -1){perror("open");exit(1);}int fd1 = open("a.txt", O_RDWR);if(fd1 == -1){perror("open");exit(1);}printf("fd = %d\n", fd);printf("fd1 = %d\n", fd1);int ret = dup2(fd1, fd); //此时先关闭fd,然后再将fd分配给a.txtif(ret == -1){perror("dup2");exit(1);}printf("current fd = %d\n", ret);char* buf = "主要看气质 ^_^!!!!!!!!!!\n";write(fd, buf, strlen(buf));write(fd1, "hello, world!", 13);close(fd);close(fd1);return 0;
}
[root@localhost dup]# ./dup2
fd = 3
fd1 = 4
current fd = 3