25.12.27 理解文件本质+文件系统调用接口+fd+重定向

文章目录

  • [1. 理解文件](#1. 理解文件)
  • [2. 系统调用接口](#2. 系统调用接口)
  • [3. 理解fd](#3. 理解fd)

1. 理解文件

文件 = 文件属性 + 文件内容

文件系统包括了加载到内存中的文件和保存在磁盘中的文件两大类

重点谈加载到内存中的文件:

根据冯诺依曼体系->文件从磁盘中加载到内存缓冲区中,等待CPU执行,这个过程由进程进行文件操作

而在代码中的体现:

研究打开的文件,本质是研究进程和文件之间的关系

2. 系统调用接口

cpp 复制代码
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>

int open(const char* pathname, int flags, mode_t mode);
  • pathname:文件路径名
  • flags:标志位,位图->32个bit位,有几个常见的宏
    • O_RDONLY:只读
    • O_WRONLY:只写
    • O_RWDWR:读写
    • O_CREAT:新建
    • O_APPEND:追加
    • O_TRUNC:清空
  • mode:设置文件权限,设置的权限要&(~umask)
cpp 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(){
  open("log.txt",O_TRUNC | O_RDWR, 666); // 清空+读写
  return 0;
}
bash 复制代码
[vect@VM-0-11-centos file]$ cat log.txt
hghhssladj
sajldjas
asld
[vect@VM-0-11-centos file]$ gcc open.c
[vect@VM-0-11-centos file]$ ./a.out 
[vect@VM-0-11-centos file]$ cat log.txt 
[vect@VM-0-11-centos file]$ 

写操作:

读操作:

关闭操作:

C的文件操作函数都是基于这四个系统调用接口封装的

3. 理解fd

文件描述符->本质是数组索引

文件加载到内存中需要管理->需要管理文件属性和文件内容->怎么管理?->先描述,再组织!

fd分配原则: 进程启动默认打开三个文件流:stdin stdout stderr 索引依次为1 2 3,新打开的文件按照未分配最小的索引开始,依次按照文件打开顺序递增分配

这里涉及到重定向:

使用dup2完成重定向

cpp 复制代码
#include <unistd.h>
int dup2(int oldfd, int newfd);

这句话的意思是newfdoldfd的拷贝,所以重定向到newfd

cpp 复制代码
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main(){
  int fd1 = open("log1.txt",O_CREAT | O_RDWR,0666);
  int fd2 = open("log2.txt",O_RDWR | O_CREAT,0666);
  int fd3 = open("log3.txt",O_RDWR | O_CREAT,0666);

  dup2(fd1,1);
  printf("%d\n",fd1);
  printf("%d\n",fd2);
  printf("%d\n",fd3);

}
bash 复制代码
[vect@VM-0-11-centos file]$ gcc dup2.c 
[vect@VM-0-11-centos file]$ ls
a.out  dup2.c  log.txt  open.c  proc.c
[vect@VM-0-11-centos file]$ ./a.out 
[vect@VM-0-11-centos file]$ ls
a.out  dup2.c  log1.txt  log2.txt  log3.txt  log.txt  open.c  proc.c
[vect@VM-0-11-centos file]$ cat log1.txt 
3
4
5

本来应该输出到显示器,但是重定向输出到文件里了

相关推荐
Yana.nice5 小时前
Linux 只保留 30 天内日志(find命令删除日志文件)
linux·运维·chrome
DFT计算杂谈9 小时前
无 Root 权限在 Tesla K80 零门槛部署 DeepSeek 大模型
linux·服务器·网络·数据库·机器学习
Zhang~Ling10 小时前
从 fopen 到 struct file:从零开始拆解 Linux 文件 I/O
linux·运维·服务器
DeeplyMind10 小时前
Linux 深入 per-VMA lock:Linux 缺页路径如何摆脱 mmap_lock
linux·per-vma lock
爱写代码的森10 小时前
蒙三方库 | harmony-utils之FileUtil文件重命名与属性查询详解
linux·运维·服务器·华为·harmonyos·鸿蒙·huawei
XMAIPC_Robot11 小时前
软硬协同实时控制|RK3588业务调度+FPGA硬件时序,ethercat实现半导体设备微秒级响应(125us)
linux·arm开发·人工智能·fpga开发
重生的黑客12 小时前
Linux 进程优先级、切换与调度:从孤儿进程到 O(1) 调度模型
linux·运维·服务器·进程优先级·nice
骑上单车去旅行13 小时前
MD5校验对比脚本
linux·服务器·windows
平生幻13 小时前
Linux 常用命令
linux
ShirleyWang01215 小时前
让headlamp控制台能访问
linux·服务器·python·k8s·k3s