dup和dup2

dup()函数和dup2()函数书上在文件操作那一章,已经讲过了,这周看重定向这块,发现它挺重要,就再看了回,记录下。

1、 dup函数
头文件及函数定义:

#include <unistd.h>
int dup(int oldfd);
 
 
  • 1
  • 2
  • dup用来复制参数oldfd所指的文件描述符。当复制成功是,返回最小的尚未被使用过的文件描述符,若有错误则返回-1.错误代码存入errno中返回的新文件描述符和参数oldfd指向同一个文件,这两个描述符共享同一个数据结构,共享所有的锁定,读写指针和各项全现或标志位。

调用dup(oldfd)等效于
fcntl(oldfd, F_DUPFD, 0)

代码示例:

#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc, char* argv[])
{
    int fd=open("text.txt", O_CREAT|O_RDWR|O_TRUNC, S_IRUSR|S_IWUSR);
    if(fd < 0)
    {
        printf("Open Error!\n");
        return 0;
    }
    int fd2=dup(fd);
    if(fd2<0)
    {
        printf("Error!\n");
        return 0;
    }
    char buf[1000];
    int n;
    while((n=read(STDIN_FILENO, buf,1000)) > 0)  //接受键盘输入,并将其存入buf所指向的缓存中   
    {
        if(write(fd2, buf, n)<n)    //将buf所指向的缓存区的n个字节的数据写入到由文件描述符fd2所指示的文件中
        {
            printf("Write Error!!\n");
            return 0;
        }
    }
    return 0;
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

STDIN_FILENO:接收键盘的输入

STDOUT_FILENO:向屏幕输出

运行结果:
这里写图片描述
从代码结果可以看出fd这个描述符指向text.txt,然后调用dup函数对 fd进行拷贝,拷贝到d2,然后write(fd2,buf,n)这句将从键盘输入到buf所指的缓冲区的数据写到 fd2所指向的文件后。所以我们在查看text.txt,看到了我们输入的东西。

2、dup2函数
头文件及其定义:

 #include <unistd.h>
 int dup2(int oldfd, int newfd);
 
 
  • 1
  • 2


  • dup2dup区别是dup2可以用参数newfd指定新文件描述符的数值。若参数newfd已经被程序使用,则系统就会将newfd所指的文件关闭,若newfd等于oldfd,则返回newfd,而不关闭newfd所指的文件。dup2所复制的文件描述符与原来的文件描述符共享各种文件状态。共享所有的锁定,读写位置和各项权限或flags等.
  • 返回值:
    若dup2调用成功则返回新的文件描述符,出错则返回-1.

dup2(oldfd, newfd)等效于
close(oldfd);
fcntl(oldfd, F_DUPFD, newfd);
在shell的重定向功能中,(输入重定向”<”和输出重定向”>”)就是通过调用dup或dup2函数对标准输入和标准输出的操作来实现的。

代码示例:

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

void main()
{
    int oldfd;
    int fd;
    int t;
    char *buf="This is a test!!!!\n";
    if((oldfd=open("mine.txt",O_RDWR|O_CREAT,0644))==-1)
    {
        printf("open error\n");
        exit(-1);
    }
    fd=dup2(oldfd,fileno(stdout));
    if(fd==-1)
    {
        printf("dup2 error\n");
        exit(-1);
    }
    printf("dup2的返回值:%d\n",fd);
    t=strlen(buf);
    if(write(fileno(stdout),buf,t)!=t)//本应该写入到stdout的信息,但是标准输出已经重定向到目标文件中,故向标准输出写的数据将会写到目标文件中。
    {
        printf("write error!\n");
        exit(-1);
    }
    close(fd);
    exit(0);
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

运行结果:
这里写图片描述
从运行结果看到本应该输出到屏幕的信息,但是标准输出已经重定向到目标文件中,故向标准输出写的数据写到了mine.txt中。

  •                     <li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#csdnc-thumbsup"></use>
                        </svg><span class="name">点赞</span>
                        <span class="count">7</span>
                        </a></li>
                        <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;popu_824&quot;}"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-csdnc-Collection-G"></use>
                        </svg><span class="name">收藏</span></a></li>
                        <li class="tool-item tool-active is-share"><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;1582594662_002&quot;}"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-csdnc-fenxiang"></use>
                        </svg>分享</a></li>
                        <!--打赏开始-->
                                                <!--打赏结束-->
                                                <li class="tool-item tool-more">
                            <a>
                            <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
                            </a>
                            <ul class="more-box">
                                <li class="item"><a class="article-report">文章举报</a></li>
                            </ul>
                        </li>
                                            </ul>
                </div>
                            </div>
            <div class="person-messagebox">
                <div class="left-message"><a href="https://blog.csdn.net/tiandc">
                    <img src="https://profile.csdnimg.cn/C/E/3/3_tiandc" class="avatar_pic" username="tiandc">
                                            <img src="https://g.csdnimg.cn/static/user-reg-year/2x/2.png" class="user-years">
                                    </a></div>
                <div class="middle-message">
                                        <div class="title"><span class="tit"><a href="https://blog.csdn.net/tiandc" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}" target="_blank">yi@ybfq</a></span>
                                            </div>
                    <div class="text"><span>发布了18 篇原创文章</span> · <span>获赞 26</span> · <span>访问量 2万+</span></div>
                </div>
                                <div class="right-message">
                                            <a href="https://im.csdn.net/im/main.html?userName=tiandc" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
                        </a>
                                                            <a class="btn btn-sm  bt-button personal-watch" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}">关注</a>
                                    </div>
                            </div>
                    </div>
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
dupdup2是Unix和Linux系统中的系统调用函数,用于复制文件描述符。 dup函数的原型为: ```c int dup(int oldfd); ``` dup2函数的原型为: ```c int dup2(int oldfd, int newfd); ``` 这两个函数的作用是将一个已有的文件描述符复制到另一个文件描述符中。 - dup函数会返回一个新的文件描述符,该描述符与参数oldfd指向同一文件表项。这意味着对返回的文件描述符的读写操作会影响到原来的文件描述符。 - dup2函数也会返回一个新的文件描述符,但是它可以指定新的文件描述符newfd。如果newfd已经被使用,那么dup2函数会先将newfd关闭,然后再复制oldfd,使得新的文件描述符与oldfd指向同一文件表项。 这两个函数通常用于重定向标准输入、输出和错误流。例如,可以使用dup2函数将标准输出重定向到一个文件中: ```c #include <unistd.h> #include <fcntl.h> int main() { int fd = open("output.txt", O_WRONLY | O_CREAT, 0644); if (fd == -1) { perror("open"); return 1; } // 将标准输出重定向到文件 if (dup2(fd, STDOUT_FILENO) == -1) { perror("dup2"); return 1; } // 打印到标准输出,实际上会写入文件 printf("Hello, world!\n"); close(fd); return 0; } ``` 在上面的示例中,dup2函数将文件描述符fd复制到标准输出描述符STDOUT_FILENO中,这样所有的printf函数调用都会将内容写入文件"output.txt"中。 希望这个解答能够帮到你!如果还有其他问题,请继续提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值