linux环境编程-文件描述符表

前面的文章我们以及介绍过PCB了,我们提及到了 一个文件描述符表,那他到底是长什么样子的呢?

我们先来看个视频了解一下

一.口述介绍

其实通常我们看到的 int fd 并不是正真的文件描述符,可以理解成代号,或许是人们这样叫久了 就把 那个 int 的 fd 叫成文件描述符了。这个fd  和真正的文件描述符 是 一个 一对一映射的关系如上图
fileno 函数把 FILE*  转成 fd   原来那个 FILE* 并没有关闭 而是逆向映射到   int   fd 
把 fd  close  了  就相当于  把  FILE*   fclose 了
但是  把  FILE*  fclose 了   在用  这个  fd 进行操作  就是 BADFD(
因为真正的文件描述符已经关闭了
 

二.我们先看一段代码验证一下我们的结论

#include <iostream>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

using namespace std;

#define FILE_NAME "tmp.txt"
#define BUF_SIZE 4096


int32_t main(int32_t argc, const char* argv[])
{
    FILE* filein;
    if(!(filein = fopen(FILE_NAME, "rw"))){
        fprintf(stderr, "the file open error ! the reason is :%s \n", strerror(errno));
        exit(-1);
    }

    char buf[BUF_SIZE];
    fgets(buf, sizeof(buf), filein);
    cout << "the infomation is :" << buf << endl;
    
    // 注意接下来的操作
    int fd = fileno(filein);
    fclose(filein);

    int size;
    size = write(fd, "嘤嘤嘤", 8);
    if(size < 0){
        fprintf(stderr, "the file open error ! the reason is :%s \n", strerror(errno));
        exit(-2);
    }


    return 0;
}

 运行结果:

猜你喜欢

转载自blog.csdn.net/qq_44065088/article/details/108558875