什么是文件描述符
對於內核而言,所有打開的文件都通過文件描述符(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 等等系統調用。
