【Linux基础IO】重定向以及原理分析

我们先来看下面一个情况:

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define filename "text.txt"
  int main()
  {
    close(1);//关闭了Liunx操作系统为我们默认打开的fd = 1的文件流stdout
    int fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if(fd < 0)
    {
      perror("open");
      return 1;
    }
    const char* arr = "hello fileoperation\n";
    int cnt = 3;
    while(cnt)
    {
      write(1, arr, strlen(arr));
      --cnt;
    }
    close(fd);
  
    return 0;
  }                       

为什么我们把fd=1的显示器文件流stdin关闭了,向fd=1的显示器文件中写入文件就会写入到text.txt里呢?这就发生了重定向,常见的重定向有:>, >>, < 。 首先得弄清楚操作系统对于文件描述符的分配规则:在task_struct里存储的指针指向的files_struct数组当中,找到当前没有被使用的最小的一个下标,作为新的文件描述符。

dup2函数

利用dup2函数进行重定向:

cpp 复制代码
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #define filename "text.txt"
   int main()
   {
    //close(1);//关闭了Liunx操作系统为我们默认打开的fd = 1的文件流stdout                                                                              
    int fd = open(filename, O_RDONLY);
    if(fd < 0)
    {
      perror("open");
      return 1;
    }
    dup2(fd, 0);
    close(fd);//关掉与不关掉都可以,因为fd已经有了一份拷贝
    char buffer[100];
    ssize_t a = read(0, buffer, sizeof(buffer)-1);
    if(a > 0)
    {
      buffer[a] = '\0';
      printf("buffer:%s\n", buffer);
    }
  
    return 0;
  }

可以看到发生了重定向。

命令行中实现重定向:

stdout与stderr

cpp 复制代码
#include <stdio.h>
   int main()
   {
     fprintf(stdout, "hello normal message\n");
     fprintf(stdout, "hello normal message\n");
     fprintf(stderr, "hello error message\n");
     fprintf(stderr, "hello error message\n");                                                                                                         
     return 0;
   }

重定向的原理分析

重定向的本质是对描述进程的task_struct里的成员指针指向的文件描述符表进行修改。

相关推荐
嘻嘻嘻开心1 分钟前
Collection接口
linux·windows·python
广东大榕树信息科技有限公司3 分钟前
机房动环管理如何通过智能可视化实现高效运维?
运维·网络·物联网·国产动环监控系统·动环监控系统
广东大榕树信息科技有限公司6 分钟前
当提升动力环境监控效率时,如何实现全面的数据集成与可视化?
运维·网络·物联网·国产动环监控系统·动环监控系统
YJlio9 分钟前
Strings 学习笔记(12.1):从二进制里“扒”出明文信息的瑞士军刀
服务器·笔记·学习
张人玉12 分钟前
c#常用的类
服务器·数据库·c#
喵叔哟17 分钟前
11.容器化与 Docker
运维·docker·容器
Suchadar17 分钟前
NAT网络地址转换
linux·服务器·网络
翼龙云_cloud42 分钟前
阿里云云渠道商:如何选择阿里云 GPU 配置方案?
服务器·人工智能·阿里云·云计算
MarkHD1 小时前
智能体在车联网中的应用:第11天 CARLA自动驾驶仿真入门:从零安装到理解客户端-服务器架构
服务器·架构·自动驾驶
旺仔Sec1 小时前
2025年安徽省职业院校技能大赛(高职组)5G组网与运维赛项竞赛样题
运维·5g