dup和dup2

来源:互联网 发布:图片上传淘宝变模糊 编辑:程序博客网 时间:2024/06/05 14:31

两个函数都可用来复制一个现存描述符

#include <unistd.h>int dup(int filedes);int dup2(int filedes, int filedes2);// 两函数的返回值:若成功返回新的文件描述符,否则返回-1

dup

先测试一个打开文件描述符

#include <fcntl.h>#include <stdio.h>int main(){    int fd;     fd = open("./test.txt", O_RDWR);    printf("fd is %d\n", fd);       return 0;}

输出:

fd is 3

文件描述符一般都是从最小可用开始的
0,1,2都分别被标准输入,输出,错误输出给占用了,所以输出3

接下来看dup实例:

#include <fcntl.h>#include <stdio.h>#include <unistd.h>int main(){    int fd, dup_fd;    char buf1[] = "hello ";    char buf2[] = "world\n";    fd = open("./test.txt", O_RDWR);    dup_fd = dup(fd);    printf("fd is %d\n", fd);     printf("dup_fd is %d\n", dup_fd);     // use fd write hello    if (write(fd, buf1, 6) != 6)    {        printf("write fd error!\n");        return 0;    }    // use dup_fd write world    if (write(dup_fd, buf2, 6) != 6)    {        printf("write dup_fd error!\n");        return 0;    }    return 0;}

输出

fd is 3dup_fd is 4

查看test.txt文件:

hello world

由上可见, dup 是复制一个最小可用文件描述符
两个文件描述符共享一个文件,如同c++中引用

dup2

看看dup2实例:

#include <stdio.h>#include <unistd.h>#include <fcntl.h>int main(){    int fd, dup_fd, dup2_fd;    fd = open("./test.txt", O_RDWR);    dup_fd = dup(fd);   //  it is 4    dup2_fd = dup2(fd, 6);  //  it should be 5, but set by 6    printf("fd: %d\ndup_fd: %d\ndup2_fd: %d\n", fd, dup_fd, dup2_fd);    return 0;}

输出:

fd: 3dup_fd: 4dup2_fd: 6

由上可见,dup2和dup函数一样,只是返回的文件描述符可以通过第二个参数”可用的文件描述符“指定。
另外,如果“可用的文件描述符“是打开状态,则会被关闭;如果”现存的文件描述符“和”可用的文件描述符“一样,则不会关闭。

0 0