# 系統程式設計 - `i_node` [TOC] ## 課程影片 ### Linux inodes Explained {%youtube 6KjMlm8hhFA %} ### UNIX Inodes and Files (Harry) {%youtube 3P8n1uC0tyI %} ### W6-2: fstat, lstat, and file systems (40:34 ~ FIN) {%youtube h4MWpyjOccg %} ### W6-3: inode, hard link and soft link, directory structur (00:00 ~ 08:53) {%youtube H1xHT9SnQHA %} ## 紀錄檔案存在硬碟的哪邊? --- inode inode 的說明可以直接查他的 [`man`](https://man7.org/linux/man-pages/man7/inode.7.html): ``` $ man inode ``` 這個文件開宗名義就說 *inode - file inode information*。並且說這是記載一個檔案相關的資訊: > **DESCRIPTION** > Each file has an inode containing metadata about the file. An application can retrieve this metadata using `stat(2)` (or related calls), which returns a stat structure, or `statx(2)`, which returns a statx structure. 檔案系統中一個邏輯上的檔案,未必是儲存在連續的實體硬體中,而是它的不同部分可會分屍儲存在不同的地方。而 inode 負責紀錄同一個檔案的不同屍塊,各自埋在哪邊: ![](https://i.imgur.com/jsLGl3E.jpg) 一個檔案系統的所有 inode 集中存放在 superblock 的前面。一個檔案系統的不同 inode 會有自己的編號。這個編號在當下的檔案系統中是唯一的,但不保證不同的檔案系統之間不會有重複的編號。這個在 `man` 裡面也有說明: > **Inode number** > Each file in a filesystem has a unique inode number. Inode numbers are guaranteed to be unique only within a filesystem (i.e., the same inode numbers may be used by different filesystems, which is the reason that hard links may not cross filesystem boundaries). This field contains the file's inode number. ### 目錄 = inode 編號的集合 目錄只是一個內容比較特別的檔案,裡面內容除了目錄的名稱之外,還紀錄著一群 i-node 編號。其中,每一個 i-node 編號都代表一個包含在該目錄之下的檔案。所以「一個目錄中有一個檔案」的意思是「這個檔案的 inode 編號出現在代表這個目錄的檔案之中」 ## 列出 i-node 資訊 根據 `inode` 的文件,一個檔案的 `inode` 中所紀錄的資訊,可以使用 `stat` 系統呼叫得知。除此之外,命令列工具的 `ls` 與 `stat` 也各自有選項可以列出來: ### `ls` 的 `--inode` 選項 檔案所對應的 i-node 編號可以使用 `ls` 的 `-i` 選項來得知。這可以在 `ls` 的 `man` 當中查到: ``` -i, --inode print the index number of each file ``` 比如說:如果某個目錄叫做 `linux`,那麼: ``` $ ls --inode linux ``` 檔案名稱最前方出現的數字,就是該檔案對應的 i-node 編號: ``` 381243 COPYING 534588 crypto 1661371 mm 381244 CREDITS 381250 cscope.files 381252 ncscope.in.out 507996 Documentation 381235 cscope.out 381257 ncscope.po.out 381245 Kbuild 381259 cscope.out.in 1661500 net 381246 Kconfig 381263 cscope.out.po 1663457 samples 517249 LICENSES 534772 drivers 1663736 scripts 381247 MAINTAINERS 546950 fs 1664223 security 381248 Makefile 549034 include 1664470 sound 381249 README 549226 init 381262 tags 517273 arch 549239 ipc 1666940 tools 534480 block 549253 kernel 1675163 usr 534575 certs 549597 lib 1783883 virt ``` ### 使用 `stat` 除了使用 `ls` 之外,`stat` 也可以列出來。舉例來說,假定有一個名稱為 `COPYING` 的檔案,想知道他的 inode 編號,則可以使用: ``` $ stat COPYING ``` 會出現類似以下的輸出: ``` File: COPYING Size: 423 Blocks: 8 IO Block: 4096 regular file Device: b302h/45826d Inode: 381243 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 1000/ ubuntu) Gid: ( 1000/ ubuntu) Access: 2021-08-18 11:31:42.185428845 +0000 Modify: 2021-08-18 11:31:42.185428845 +0000 Change: 2021-08-18 11:31:42.185428845 +0000 Birth: - ``` 這當中的 `Inode` 欄位就是該 `COPYING` 檔案的 inode。 > 在上述 `stat` 的輸出欄位中,有一個 `Links` 欄位。這會跟下一個影片的 Hard Link 有關。