Linux系统编程——dup() 重定向函数

这篇文章讲的是linux系统编程中的重定向函数,这个函数的作用是将一个文件描述符指向另一个文件描述符,有点像指针的作用,比如:fd2 指向 fd1,你改变 fd2 的文件内容,就可以直接改变fd1的内容,fd2是指向fd1的。

在这里插入图片描述

1、dup()

int dup(int oldfd);		//文件描述符复制。
//oldfd: 已有文件描述符
//返回值:新文件描述符,这个描述符和oldfd指向相同内容。

代码示例:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<pthread.h>
#include<unistd.h>

int main()
{
        int fd1 = open("abc.c", O_RDWR | O_CREAT); //创建并打开文件
        if(fd1 == -1)
        {
                perror("open error");
                exit(1);
        }

        int fd2 = dup(fd1);	//产生一个新的文件描述符,使其指向旧的文件描述符fd1
        if(fd2 == -1)
        {
                perror("dup error");
                exit(1);
        }

        write(fd2, "hello world!\n", 13);
        //向fd2文件描述符写数据,最终写入到放fd1中,也就是打开的abc.c文件中
        return 0;
}

效果:
在这里插入图片描述

2、dup2()

int dup2(int oldfd, int newfd); 
//文件描述符复制,oldfd拷贝给newfd。返回newfd==>全是oldfd
//返回值就是newfd,不过也是指向oldfd

代码示例:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<pthread.h>
#include<unistd.h>

int main()
{
        //创建并打开两个文件
        int fd1 = open("abc.c", O_RDWR | O_CREAT);
        int fd2 = open("efg.c", O_RDWR | O_CREAT);

        //将fd2重点向到fd1
        int newfd = dup2(fd1, fd2);
        if(newfd == -1)
        {
                perror("dup2 error");
                exit(1);
        }

        write(newfd, "hello world!\n", 13);
        write(fd2, "good monring!\n", 14);//fd2和newfd都是指向fd1的
        return 0;
}

效果:
在这里插入图片描述

注:因为fd2已经指向fd1,所以利用fd2输入数据,只能输入到abc.c文件里面,不能输入到efg.c里面。

3、fcntl实现dup

  • 这个函数我之前的文章就已经讲过了,这里只是参数不同就可以实现dup了。
    在这里插入图片描述

翻译:
找到大于或等于arg的编号最低的可用文件描述符,并使其成为fd的副本。这与dup2(2)不同,后者恰恰使用
描述符指定。
成功时,将返回新的描述符。

作用就是个dup函数一样的。

代码示例:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<pthread.h>
#include<unistd.h>

int main()
{
        int fd1 = open("abc.c", O_RDWR | O_CREAT);
        if(fd1 == -1)
        {
                perror("open error");
                exit(1);
        }

        int fd2 =fcntl(fd1, F_DUPFD, 0);
        if(fd2 == -1)
        {
                perror("dup error");
                exit(1);
        }
        write(fd2, "the world!\n", 13);
        return 0;
}

这个代码的效果和上面的一样。

好了关于这个函数就分享到这了。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白学编程*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值