文件描述符

文件描述符

对于内核而言,所有打开的文件都通过文件描述符(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 等等系统调用。


千里之行,始于足下
本站总访问量 本文总阅读量