dup 和dup2 都可用来复制一个现存的文件描述符,使两个文件描述符指向同一个file 结构体。如果两个文件描述符指向同一个file 结构体,File Status Flag和读写位置只保存一份在file 结构体中,并且file 结构体的引用计数是2。如果两次open 同一文件得到两个文件描述符,则每个描述符对应一个不同的file 结构体,可以有不同的File Status Flag和读写位置。 |
有人在网上是这样写的,不知道其确切的出处,不过我也认同这种说法.下面是我自己写的一个测试程序,主要测试了dup2的用法,实现输出的重定向:
#include |
编译运行:
$ gcc -o dup2 dup2.c
$ ./dup2 tempfd:3, tempfd2:4 this is tempfd2 file! tempfd2 closed! Write this to stderr useing fprintf function after close the tempfd! Write this to stderr useing fprintf function after close the 1! $ cat /tmp/dup2 Write this to stdout with printf function! Write this to stdout useing fprintf function! Write this to stdout useing fprintf function after close the tempfd! |