dup and dup2

1353阅读 0评论2010-11-15 whj2819
分类:LINUX

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

dup 和dup2 都可用来复制一个现存的文件描述符,使两个文件描述符指向同一个file 结构体。如果两个文件描述符指向同一个file 结构体,File Status Flag和读写位置只保存一份在file 结构体中,并且file 结构体的引用计数是2。如果两次open 同一文件得到两个文件描述符,则每个描述符对应一个不同的file 结构体,可以有不同的File Status Flag和读写位置。(网上看到的)

=============================================

fd = dup(1);//1-标准输出,对文件描述符fd的操作将输出至标准输出.

int main(void){
    int fd = -1;
    int fd2 = -1;

    fd = open("/tmp/dup",O_RDWR | O_CREAT,0644);
    if(fd < 0){
        printf("open /tmp/dup file faile!\n");
        }
#if 0
     fd = dup(1);//对fd的操作,数据直接重定向到标准输出
     write(fd,"this is a test!\n",16);
     printf("Begin:Write these to stdout!\n");
     fprintf(stdout,"Write second strings!\n");
     close(fd);
#endif
    dup2(fd,1);//对标准输入的操作将数据直接输入到文件描述符fd

               // 对应的文件中去。

    write(fd,"this is a test!\n",16);
    printf("Writer to /tmp/dup file!\n");
    close(fd);
    printf("close fd\n");// 这行会显示在哪里呢,当然是自己建立的

    //文件中,因为标准输出和fd共享一个文件表(File Table)

    close(1);
    printf("close stdout!!\n");//不会有任何显示

     return 0;

}

========================================================

cat /tmp/dup
this is a test!
Writer to /tmp/dup file!
close fd

========================================================

以上是我对它们的一点理解吧,有不对的地方望大牛们多多指点 ^ ^

上一篇:sizeof and strlen
下一篇:Const