#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