萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 檔案 I/O 核心機制深度解析:檔案描述符、open/read/write/lseek/close 系統呼叫與核心資料結構

Linux 檔案 I/O 是系統程式設計的基石。本文從檔案描述符、五大核心系統呼叫 (open/read/write/lseek/close)、核心三層資料結構 (進程檔案描述符表、系統級檔案表、v-node/i-node 表) 全方位剖析,並附完整 C 語言實戰範例,建立扎實的底層 I/O 觀念。

一、檔案描述符

  • 非負整數,進程內部索引開啟檔案的鍵值。
  • 每個進程預設開啟三個標準描述符:

open 回傳最小未使用描述符編號,此特性常用於重導向實作。

二、核心系統呼叫詳細規範

1. open - 開啟/建立檔案

#include 
#include 
#include 

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

必要旗標 (三選一):O_RDONLY 唯讀、O_WRONLY 唯寫、O_RDWR 讀寫。

常用選用旗標組合:

  • O_CREAT:不存在則建立,需第三參數 mode 指定權限 (如 0644)。
  • O_EXCL:配合 O_CREAT,檔案存在則報錯 (原子性建立)。
  • O_TRUNC:截斷現有檔案長度為 0 (需寫入權限)。
  • O_APPEND:寫入追加至檔案尾端。

回傳:成功回傳檔案描述符,失敗回傳 -1 並設定 errno。

2. close - 關閉檔案描述符

#include 
int close(int fd);
  • 釋放描述符,解除進程與檔案關聯,釋放該進程持有的所有記錄鎖。
  • 進程終止時核心自動關閉所有開啟描述符。

3. lseek - 重新定位檔案偏移量

#include 
#include 
off_t lseek(int fd, off_t offset, int whence);

whence 取值:

  • SEEK_SET:從檔案開頭偏移 offset 位元組。
  • SEEK_CUR:從目前位置偏移 offset 位元組。
  • SEEK_END:從檔案結尾偏移 offset 位元組 (通常為負值)。

可建立「檔案洞」 (offset > 檔案長度),不佔實體磁碟空間。

4. read - 讀取資料

#include 
ssize_t read(int fd, void *buf, size_t count);
  • 回傳實際讀取位元組數 (可能 < count),0 表示 EOF,-1 表示錯誤。
  • 讀取後檔案偏移量自動前移。

5. write - 寫入資料

#include 
ssize_t write(int fd, const void *buf, size_t count);
  • 回傳實際寫入位元組數,通常等於 count;不足表示錯誤 (如磁碟滿、配額超限)。
  • 寫入後檔案偏移量自動前移 (除非 O_APPEND)。

三、核心三層資料結構與檔案共享

核心維護三層結構支援多進程檔案共享:

  1. 進程檔案描述符表:每進程一張,索引為 fd,項目含 fd_flags (如 FD_CLOEXEC) 與指向系統檔案表的指標。
  2. 系統級檔案表 (Open File Table):全系統共享,每項含 file_status_flags (O_RDWR, O_APPEND...)、current_file_offset、指向 v-node 表的指標。fork() 後父子進程共享同一檔案表項,故共享偏移量。
  3. v-node/i-node 表:每開啟檔案一項,含檔案類型、操作函數指標、i-node (擁有者、權限、時間戳、資料塊指標)。

核心檔案資料結構關係圖

四、完整實戰範例:建立檔案、寫入、定位讀取

#include 
#include 
#include 
#include 
#include 

int main() {
    char *filename = "./testfile";
    char buf[100], buf1[5];
    int fd;

    printf("open a file to write\n");
    if ((fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) == -1) {
        perror("cannot open file");
        return 1;
    }
    printf("open file successfully!\n");
    printf("input a string: ");
    fgets(buf, sizeof(buf), stdin);  // 安全替代 gets()
    buf[strcspn(buf, "\n")] = 0;     // 移除換行

    if (write(fd, buf, strlen(buf)) != strlen(buf)) {
        perror("cannot write into file");
        return 1;
    }
    close(fd);

    printf("open file to read.\n");
    if ((fd = open(filename, O_RDONLY)) == -1) {
        perror("cannot open the file");
        return 1;
    }
    if (lseek(fd, 3, SEEK_SET) == -1) {
        perror("lseek error");
        return 1;
    }
    if (read(fd, buf1, 4) == -1) {
        perror("read error");
        return 1;
    }
    printf("read from file is: %s\n", buf1);
    close(fd);
    return 0;
}

編譯執行:

gcc -o io io.c
./io

輸出範例:

open a file to write
open file successfully!
input a string: akxivbaslzkncxcasbxbwwvaidxbd
open file to read.
read from file is: ivba

解析:寫入完整字串,lseek(fd,3,SEEK_SET) 移至第 4 字元,讀取 4 字元 ivba。

五、進階主題預告

  • 檔案鎖 (fcntl/flock) 實現進程同步。
  • 非阻塞 I/O (O_NONBLOCK) 與多路複用 (select/poll/epoll)。
  • 記憶體映射 I/O (mmap) 零拷貝高效資料傳輸。

結語:掌握檔案描述符語義、五大系統呼叫行為與核心三層資料結構關係,是編寫高效、健壯 Linux 系統程式的基石。

copyright © 萬盛學電腦網 all rights reserved
值名稱巨集常數用途
0標準輸入STDIN_FILENO鍵盤/管道輸入
1標準輸出STDOUT_FILENO螢幕/管道輸出
2標準錯誤STDERR_FILENO錯誤訊息輸出