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;
}

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

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


版权声明:本文为weixin_67452474原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。