Chinaunix首页 | 论坛 | 博客
  • 博客访问: 190341
  • 博文数量: 39
  • 博客积分: 1491
  • 博客等级: 上尉
  • 技术积分: 411
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-05 16:12
文章分类

全部博文(39)

文章存档

2011年(3)

2010年(6)

2009年(30)

我的朋友

分类: LINUX

2010-01-28 18:56:24

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 < 0)
        printf ("open file /tmp/dup2 failed\n");

    tempfd2 = open ("/tmp/dup2", O_RDWR | O_CREAT, 0644);
    if (tempfd < 0)
        printf ("once open file /tmp/dup2 failed\n");

    printf ("tempfd:%d, tempfd2:%d\n", tempfd, tempfd2);
    close (tempfd2);

    tempfd2 = dup (1);
    write (tempfd2, "this is tempfd2 file!\n", 22);
    close (tempfd2);
    printf ("tempfd2 closed!\n");

    dup2 (tempfd, 1);

    printf ("Write this to stdout with printf function!\n");
    fflush (NULL);
    fprintf (stdout, "Write this to stdout using fprintf function!\n");

    fflush (NULL);
    close (tempfd);

    fprintf (stderr, "Write this to stderr using fprintf function after close the tempfd!\n");
    fflush (NULL);
    fprintf (stdout, "Write this to stdout using fprintf function after close the tempfd!\n");
    fflush (NULL);
    close (1);
    fprintf (stderr, "Write this to stderr using fprintf function after close the 1!\n");
    fflush (NULL);
    fprintf (stdout, "Write this to stdout using fprintf function after close the 1!\n");
    fflush (NULL);
    return 0;
}


编译运行:

$ 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!



阅读(2780) | 评论(1) | 转发(0) |
0

上一篇:Unix编程[二] read

下一篇:linux线程浅析

给主人留下些什么吧!~~

whj28192010-11-15 20:18:20

不错的例子 ^ ^