linux 学习之应用程序和网络编程笔记(中)

一、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()


发布了41 篇原创文章 · 获赞 2 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章