007dup重定向文件描述符_LINUX

dup、dup2 重定向文件描述符

duplicate a file descriptor

1. dup()、dup2()

  • dup
    复制一份文件描述符,返回的文件描述符是当前环境的最低值

  • dup2
    将旧文件描述符,复制给新的指定描述符,并返回新的指定文件描述符

头文件包含及函数声明(man 2 dup)

#include<unistd.h>

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

2. dup 的demo

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

int main(int argc,char* argv[])
{
        int fd = open(argv[1], O_RDWR);

        int newfd = dup(fd);

        printf("newfd = %d\n", newfd);

        write(newfd, "123456", 6);
        return 0;
}

3. dup 使不同的文件符指向了同一个文件

在这里插入图片描述

4. dup2 demo

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

int main( int argc, char* argv[])
{
        int fd1 = open(argv[1], O_RDWR);
        int fd2 = open(argv[2], O_RDWR);

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

        int ret = write(fd2, "123456\n", 7);
        printf("ret = %d\n", ret);

        dup2(fd1, STDOUT_FILENO);

        printf("------------886\n");

        return 0;
}

5. fcntl 实现 dup

fcntl 头文件包含及函数声明

fcntl:对文件描述符进行操作(man 2 fcntl )

#include<unistd.h>
#include<fcntl.h>

int fcntl(int fd, int cmd,.../* arg */

cmd:F_DUPFD

参数3:

  • 被占用的,返回最小可用的
  • 未被占用,返回等于该值的文件描述符

fcntl 实现 dup demo

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

int main(int argc, char* argv[])
{
        int fd1 = open(argv[1], O_RDWR);

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

        int newfd = fcntl(fd1, F_DUPFD, 0); // 0 被占用,fcntl 使用文件描述符表中可用最小文件描述符返回
        printf("newfd = %d\n", newfd);

        int newfd2 = fcntl(fd1, F_DUPFD, 7); // 7,未被占用,返回文件描述符 7
        printf("newfd2 = %d\n", newfd2);

        int ret = write(newfd2, "YYYYYY", 7);
        printf("ret = %d", ret);
        return 0;
}


成功!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值