Wednesday, January 26, 2011

Unix编程[三] dup dup2

Unix编程[三] dup dup2 (2010-01-28 18:56) 
轉:http://blog.chinaunix.net/space.php?uid=20791382&do=blog&cuid=2163440
分类: Unix编程

dup 和dup2 都可用来复制一个现存的文件描述符,使两个文件描述符指向同一个file 结构体。如果两个文件描述符指向同一个file 结构体,File Status Flag和读写位置只保存一份在file 结构体中,并且file 结构体的引用计数是2。如果两次open 同一文件得到两个文件描述符,则每个描述符对应一个不同的file 结构体,可以有不同的File Status Flag和读写位置。
       
      有人在网上是这样写的,不知道其确切的出处,不过我也认同这种说法.下面是我自己写的一个测试程序,主要测试了dup2的用法,实现输出的重定向:

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

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!


No comments:

Post a Comment