dup和dup2函数

#include <unistd.h>

int dup(int oldfd);

int dup2(int oldfd, int newfd);

作用:dup函数实现对一个文件的文件描述符进行复制,复制之后该进程就会新增加一一个文件描述符指向该文件(即实现同一个文件对应多个文件描述符)。dup2函数:如果new是一个被打开的文件描述符(与old不是同一个文件),则在拷贝前先关闭new(new就不需要占据那个文件描述符了),即使new文件的文件描述符重新指向old文件;如果两个文件描述符对应的是同一个文件,则直接返回文件描述符。  文件描述符的复制又称为文件描述符的重定向。

dup返回值:返回新的文件描述符(文件描述符表中最小的未被占用的文件描述符)。 出错,返回-1。

dup2返回值:如果两个文件描述符对应的是同一个文件,则直接返回文件描述符。(不拷贝)。如果不是同一个文件,则返回new的那个文件描述符。出错 返回-1。

//dup函数代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd = open("a.txt", O_RDWR); //文件第一次被打开时,其文件指针置于文件首部
    if(fd == -1)
    {
        perror("open");
        exit(1);
    }

    printf("file open fd = %d\n", fd);

    int ret = dup(fd);  //文件描述符的复制(重定向)
    if(ret == -1)
    {
        perror("dup");
        exit(1);
    }
    printf("dup fd = %d\n", ret);
    char* buf = "你是猴子派来的救兵吗????\n";
    char* buf1 = "你大爷的,我是程序猿!!!\n";
    write(fd, buf, strlen(buf));  //通过fd来向文件写入数据
    write(ret, buf1, strlen(buf1));  //通过ret来向同一文件继续写入数据,注意是追加写入,因为一个文件的文件读写指针只有一个,因此第一个文件操作后,第二个接着第一个的位置继续进行。

    close(fd);  //此时只是释放了fd,但还是可以通过ret来使用该文件。
    close(ret);  //释放ret
    return 0;
}

//dup2函数代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main( )
{
    int fd = open("english.txt", O_RDWR);
    if(fd == -1)
    {
        perror("open");
        exit(1);
    }

    int fd1 = open("a.txt", O_RDWR);
    if(fd1 == -1)
    {
        perror("open");
        exit(1);
    }

    printf("fd = %d\n", fd);
    printf("fd1 = %d\n", fd1);

    int ret = dup2(fd1, fd);  //此时先关闭fd,然后再将fd分配给a.txt
    if(ret == -1)
    {
        perror("dup2");
        exit(1);
    }
    printf("current fd = %d\n", ret);
    char* buf = "主要看气质 ^_^!!!!!!!!!!\n";
    write(fd, buf, strlen(buf));
    write(fd1, "hello, world!", 13);

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

[root@localhost dup]# ./dup2

fd = 3

fd1 = 4

current fd = 3

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值