免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1330 | 回复: 0
打印 上一主题 下一主题

Unix编程[三] dup dup2 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-01-28 18:56 |只看该作者 |倒序浏览

                                                                                dup 和dup2 都可用来复制一个现存的文件描述符,使两个文件描述符指向同一个file 结构体。如果两个文件描述符指向同一个file
结构体,File Status Flag和读写位置只保存一份在file 结构体中,并且file 结构体的引用计数是2。如果两次open
同一文件得到两个文件描述符,则每个描述符对应一个不同的file 结构体,可以有不同的File Status Flag和读写位置。        
      有人在网上是这样写的,不知道其确切的出处,不过我也认同这种说法.下面是我自己写的一个测试程序,主要测试了dup2的用法,实现输出的重定向:
#include
#include
#include
int
main (int argc, char **argv)
{
    int tempfd = -1;
    int tempfd2 = -1;
    tempfd = open ("/tmp/dup2", O_RDWR | O_CREAT, 0644);
    if (tempfd
编译运行:
$ 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!
               
               
               
               
               
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/87597/showart_2163440.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP