一、dup 和dup2
int dup(int oldfd);
dup系統調用對文件描述符進行復制,會返回一個新的文件描述符,譬如原來的fd是3 ,則返回的是4 (dup返回的文件描述符是該進程未使用的最小的文件描述符)
該兩個文件描述符都指向oldfd打開的文件,實際上構成了文件共享,對其進行讀寫,其實是接續寫。
使用dup的缺陷:使用dup時不能指定返回的文件描述符數字,而dup2可以彌補這一點
int dup2(int oldfd, int newfd);
dup2和dup都是一樣複製文件描述符 ,但是dup2可以指定複製某個文件描述符
dup2() makes newfd be the copy of oldfd, closing newfd first if neces‐
sary, but note the following:
* If oldfd is not a valid file descriptor, then the call fails, and
newfd is not closed.
* If oldfd is a valid file descriptor, and newfd has the same value as
oldfd, then dup2() does nothing, and returns newfd.
比如打開一個文件返回lodfd=3;然後使用 newfd=dup2(oldfd,15);則會將oldfd文件描述符複製到新的文件描述符15中 ,則newfd=15,儘管這兩個文件描述符不一樣,但是這兩個文件描述符結構是一樣的,用的同一個文件指針 所以讀寫是接續讀寫。
(二)標準IO
fopen()