dup和dup2函数

dup和dup2函数

dupdup2用于复制文件描述符,通常用于重定向。

#include <unistd.h>

int dup(int oldfd);
int dup2(int oldfd, int newfd);

dup函数创建一个新的文件描述符,该新文件描述符和原有文件描述符oldfd指向相同的文件、管道或者网络连接。并且dup返回的文件描述符总是取系统当前可用的最小整数值。

dup2dup类似,不过它将返回第一个不小于newfd的整数值的文件描述符,并且newfd这个文件描述符也将会指向oldfd指向的文件,原来的newfd指向的文件将会被关闭(除非newfdoldfd相同)。

dupdup2系统调用失败时返回-1并设置errno,成功就返回新的文件描述符。

注意:通过dup和dup2创建的文件描述符并不继承原文件描述符的属性,比如close-on-exec和non-blocking 等

dup简单,输入oldfd直接返回复制的文件描述符

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
int main(int argc, char const *argv[])
{
    int fd = open("text.txt", O_RDWR | O_CREAT, 0666);
    assert(fd != -1);
    printf("fd = %d\n", fd);

    int fd2 = dup(fd);
    printf("fd2 = %d\n", fd2);

    char str[] = "hello ";
    write(fd, str, sizeof(str));
    char str2[] = "world\n";
    write(fd2, str2, sizeof(str2));

    close(fd);
    close(fd2);
    return 0;
}

image-20220815171158327

dup2感觉复杂一些,其实dup2忽略第二个参数,功能是和dup一样的,除此之外dup2加了一个将返回第一个不小于newfd的整数值的文件描述符的功能,并且newfd也将指向oldfd指向的文件。

下面的代码调用dup2,文件描述符fd2原来指向"text2.txt"文件的,调用dup2后,fd2改为指向"text.txt"。

image-20220815173243219

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
int main(int argc, char const *argv[])
{
    int fd1 = open("text.txt", O_RDWR | O_CREAT, 0666);
    int fd2 = open("text2.txt", O_RDWR | O_CREAT, 0666);

    assert(fd1 != -1);
    assert(fd2 != -1);
    printf("fd1 = %d, fd2 = %d\n", fd1, fd2);

    int fd3 = dup2(fd1, fd2);
    printf("fd1 = %d,fd2 = %d,fd3 = %d\n", fd1, fd2, fd3);

    char str[] = "hello ";
    write(fd1, str, sizeof(str));
    char str2[] = "world\n";
    write(fd2, str2, sizeof(str2));
    char str2[] = " hello world\n";
    write(fd3, str2, sizeof(str2));

    close(fd1);
    close(fd2);
    close(fd3);

    return 0;
}

image-20220815173321291

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值