linux系统编程之文件与IO(八):文件描述符相关操作-dup,dup2,fcntl


本节目标:

1,文件共享

  • 打开文件内核数据结构
  • 一个进程两次打开同一个文件
  • 两个进程打开同一个文件

2,复制文件描述符(dup、dup2、fcntl)

 

一,文件共享

1,一个进程打开两个文件内核数据结构

:每个进程都有一张,彼此独立,每个文件描述符表项都指向一个文件表,文件描述符0(STDIN_FILENO)、1(STDOUT_FILENO)、2(STDERR_FILENO),默认已经打开,分别表示:标准输入,标准输出,标准错误设备。

:每打开一个文件就对应一张文件表,文件表可以共享,当多个文件描述符指向同一个文件表时,文件表中的

refcnt字段会相应变化。文件状态标识:文件的打开模式(R,W,RW,APPEND,NOBLOCK,等),当前文件偏移量,refcnt:被引用数量,

v节点指针:指向一个v节点表。

:每个文件对应一个,无论被被多少个进程打开都只有一个,它包括v节点信息(主要是stat结构体中的信息),i节点信息。

每个进程默认只能打开1024个文件描述符,当一个进程打开一个文件时,默认会从0开始查找未被使用的描述符,由于0,1,2默认被占用,所有一般从3开始使用。

2、一个进程两次打开同一个文件

<sys/stat.h><sys/types.h><sys/stat.h><fcntl.h><stdlib.h><stdio.h><errno.h><.h> ERR_EXIT(m) \ ( main( argc, * buf1[] = { buf2[] = {= open( (fd1 == -= open( (fd2 == -, ,

运行结果:

1,dup

2,dup2

#include <unistd.h>

int dup(int oldfd);
int dup2(int oldfd, int newfd);

DESCRIPTION
       These system calls create a copy of the file descriptor oldfd.

       dup()  uses  the lowest-numbered unused descriptor for the new descriptor.

       dup2() makes newfd be the copy of oldfd, closing newfd first if  necessary, 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.

       After  a  successful return from one of these system calls, the old and new file descriptors may be used interchangeably.  They  refer  to  the same open file description (see open(2)) and thus share file offset and file status flags; for example, if the file offset is modified by using lseek(2)  on one of the descriptors, the offset is also changed for the other.

RETURN VALUE
       On success, these system calls return the new descriptor.  On error, -1 is returned, and errno is set appropriately.

示例程序:

#include <stdio.h><unistd.h><stdlib.h><fcntl.h>


 main(= open(( fd == -=(fd2 == -); 
    fd3 =(fd3 == -

运行结果:

<unistd.h><stdlib.h><fcntl.h> main(= open(( fd == -= dup2(fd,(fd2 == -

运行结果:

  or  equal to arg and make it be a copy of fd.  This is different
from dup2(2), which uses exactly the descriptor specified.

  On success, the new descriptor is returned.

示例程序:

#include <unistd.h><sys/stat.h><sys/types.h><sys/stat.h><fcntl.h><stdlib.h><stdio.h><errno.h><.h>

 ERR_EXIT(m) \
    ( main( argc,  *= open( (fd == - (fcntl(fd, F_DUPFD, ) < );
     

运行结果:

QQ截图20130711163716

相关内容