文件描述符是什么

什么是文件描述符

对于内核而言,所有打开的文件都通过文件描述符(file descriptor)引用。通常也写作 fd

文件描述符是一个非负整数。

当打开一个现有文件或者创建一个新文件时,内核向进程返回一个文件描述符

文件描述符是跟进程相关联的。

按照惯例,UNIX 系统将 fd 0 对应进程的标准输入, fd 1 对应进程的标准输出, fd 2 对应进程的标准错误。

系统调用中的文件描述符

UNIX 系统中,一切皆文件,所以一切资源都可以使用文件描述符进程引用。

open 系统调用为例

使用 man 2 open 查看系统 man 手册

NAME
open, openat -- open or create a file for reading or writing
SYNOPSIS
#include <fcntl.h>
int
open(const char *path, int oflag, ...);
int
openat(int fd, const char *path, int oflag, ...);
DESCRIPTION
The file name specified by path is opened for reading and/or writing,
as specified by the argument oflag; the file descriptor is returned to
the calling process.

在简介中有一段话:the file descriptor is returned to the calling process.

使用 c 语言打开一个 文件

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd;
fd = open("tmp.txt", O_RDONLY);
printf("%d", fd);
sleep(10);
}

会发现,在进程运行时 fd 目录下,会出现一个描述符 3 指向了 打开的文件

$ ll /proc/$(ps aux | grep a.out | grep -v grep | awk '{print $2}')/fd
total 0
lrwx------ 1 ubuntu ubuntu 64 Apr 13 13:48 0 -> /dev/pts/4
lrwx------ 1 ubuntu ubuntu 64 Apr 13 13:48 1 -> /dev/pts/4
lrwx------ 1 ubuntu ubuntu 64 Apr 13 13:48 2 -> /dev/pts/4
lr-x------ 1 ubuntu ubuntu 64 Apr 13 13:48 3 -> /home/ubuntu/mydisk/yangblog/codes/file/tmp.txt

我们可以把这个文件描述符当做参数传递给 read 或者 write 等等系统调用。

posted @   吴丹阳-V  阅读(1098)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示