Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 系統開發(6):Linux 底層輸入輸出

編輯:關於 Android 程式設計

一、操作系統的體系結構

計算機由一堆硬件組成,操作系統是為了有效控制這些硬件資源的軟件。除了有效控制硬件資源的分配、並提供計算機運行所需的功能之外,為了給程序員提供更易開發軟件的環境,操作系統還提供了一整組系統調用接口。

如上圖所示,最中間的是硬件,操作系統由內核和系統調用接口組成。其中內核直接操作硬件,負責對硬件資源的控制和進程管理;系統調用接口向上提供統一的調用接口,方便開發人員調用。最上層則是應用程序,在應用程序中調用系統接口,就能實現對硬件的操作。

二、Linux I/O 系統

如上圖 Linux 的 I/O 系統結構圖所示,內核層有一個虛擬文件系統,它使用標準的 C 類庫封裝的 API,所以我們要操作文件系統,只需調用這裡的 API 即可。

三、I/O 的操作過程

1、打開文件:一個應用程序通過要求內核打開相應的文件,宣告它要訪問一個 I/O 設備。內核返回一個非負整數,叫做文件描述符(File Descriptor)。後續對該文件的所有操作,都通過這個描述符來引用。

打開文件通常涉及 open、creat 等系統調用;關閉文件則使用 close。當不再需要某文件時,通過 close 釋放對應的描述符資源。

四、Linux 底層輸入輸出

我們可以去 GNU 下載 libc 的源代碼和幫助文檔(源碼下載地址:https://ftp.gnu.org/gnu/glibc/)。

打開和關閉文件流:

 #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
    // open file
    if(argc < 2){
        printf("please input filename\n");
        exit(1);
    } else {
        int fd;
        umask(0000);
        fd = open(argv[1], O_RDWR | O_CREAT, 0666);
        if(fd < -1){
            printf("error\n");
            exit(1);
        } else {
            printf("success=%d\n", fd);
            close(fd);
            printf("closed\n");
        }
    }
    return 0;
}

讀文件(寫文件的過程與讀文件類似):

 #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){
    // open file
    if(argc < 2){
        printf("please input filename\n");
        exit(1);
    } else {
        int fd;
        umask(0000);
        fd = open(argv[1], O_RDWR | O_CREAT, 0666);
        if(fd < -1){
            printf("error\n");
            exit(1);
        } else {
            printf("success=%d\n", fd);
            char buf[1024];
            memset(buf, 0, 1024);
            int returnum = read(fd, buf, 1024);
            if(returnum != -1){
                printf("buf=%s\n", buf);
            } else {
                printf("read error\n");
                exit(1);
            }
            close(fd);
            printf("closed\n");
        }
    }
    return 0;
}

總的來說,Linux 的底層 I/O 通過 open 獲取文件描述符、read/write 進行讀寫、close 釋放資源,構成了最基礎也最直接的文件操作方式。理解這套機制,是深入學習 Android 系統底層的重要基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved