Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 磁碟自檢(fsck)完整解析

Linux 開機偶爾會慢得讓人冒汗,追下去往往發現時間都耗在磁碟自檢(fsck)上。下面用 RHEL Server 5.7 為例,把「為什麼要自檢、什麼時候會自檢、怎麼調整與關閉、如何強制自檢」一次講清楚(不同版本細節請自行留意差異)。

Linux 磁碟自檢(fsck)完整解析

為什麼磁碟需要自檢?

現代檔案系統已經相當可靠,但停電、硬體故障等意外仍會破壞一致性,因此 Linux 用 fsck(filesystem consistency check,檔案系統一致性檢查)來檢查並修復。它能安全且自動地處理五類問題:未被參照的 inode、異常龐大的連結數、未出現在磁碟區塊映射表中的未用區塊、仍被某檔案使用卻標記為空閒的區塊,以及超級區塊中不正確的統計資訊。

開機時系統通常以 fsck -p 檢查 /etc/fstab 中列出的所有本地檔案系統,目的是在系統投入使用前把錯誤修掉——帶著錯誤的檔案系統繼續運作只會讓情況更糟。所以除非有特殊理由,不建議關閉磁碟自檢。

什麼時候才會觸發自檢?

並非每次重啟都做,規律由 tune2fs 決定:

[root@DB-Server ~]# tune2fs -l /dev/sda2 | grep -E "Maximum mount count|Check interval"
Maximum mount count: -1
Check interval: 604800 (1 week)

Linux 磁碟自檢(fsck)完整解析

Check interval 是自檢的時間間隔(這裡是 7 天),Maximum mount count 則是強制自檢的掛載次數門檻;數值 -1 代表停用該機制。

如何調整自檢設定?

把間隔改為一個月:

[root@DB-Server ~]# tune2fs -i 30 /dev/sda2
tune2fs 1.39 (29-May-2006)
Setting interval between checks to 2592000 seconds
[root@DB-Server ~]# tune2fs -l /dev/sda2 | grep -iE 'mount|check'
Mount count: 94
Maximum mount count: -1
Check interval: 2592000 (1 month)

Linux 磁碟自檢(fsck)完整解析

改成掛載兩次就強制自檢:

[root@DB-Server ~]# tune2fs -c 2 /dev/sda2
Setting maximal mount count to 2

Linux 磁碟自檢(fsck)完整解析

兩個條件也可以一次設定:

[root@DB-Server ~]# tune2fs -i 60 -c 10 /dev/sda2
Setting maximal mount count to 10
Setting interval between checks to 5184000 seconds

如何關閉自檢?

方法一:tune2fs 歸零

[root@DB-Server ~]# tune2fs -i 0 -c 0 /dev/sda2
Setting maximal mount count to -1
Setting interval between checks to 0 seconds

此後 Check interval 顯示 0(<none>),Maximum mount count 為 -1。

方法二:修改 /etc/fstab 第六欄

第六欄(pass)決定自檢順序:0 表示不自檢,1 或 2 表示要自檢,根分區設 1,其餘只能是 2。

LABEL=/ / ext3 defaults 1 1
LABEL=/boot /boot ext3 defaults 1 2
/dev/VolGroup02/LogVol00 /u05 ext3 defaults 1 2

改為:

LABEL=/ / ext3 defaults 1 0
LABEL=/boot /boot ext3 defaults 1 0
/dev/VolGroup02/LogVol00 /u05 ext3 defaults 1 0

實測結論:即使 tune2fs 的條件已經滿足,只要在 /etc/fstab 中關閉自檢,重啟時就不會做——fstab 的優先級更高。

方法三:開機參數 -f 跳過(臨時)

[root@DB-Server ~]# shutdown -rf now

這種做法不改任何設定,只用於當次開機。

方法四:在 grub.conf 加上 fastboot

於 kernel 或 initrd 行尾追加 fastboot 即可,例如:

kernel /vmlinuz-2.6.18-274.el5 ro root=LABEL=/ rhgb quiet
initrd /initrd-2.6.18-274.el5.img fastboot

如何強制下次開機自檢?

做法一:調整 Maximum mount count 與 Check interval,讓下次開機剛好命中條件。

做法二:建立 /forcefsck 檔案。RHEL 在 /etc/rc.sysinit 中會檢查這個檔案(Debian/Ubuntu 則看 /etc/init.d/checkfs.sh)。

Linux 磁碟自檢(fsck)完整解析

[root@DB-Server /]# touch /forcefsck
[root@DB-Server /]# reboot

重啟過程中即可看到自檢,完成後該檔案會自動消失。

Linux 磁碟自檢(fsck)完整解析

做法三:使用 shutdown 的 F 參數。

Linux 磁碟自檢(fsck)完整解析

# shutdown -rF now

參考資料:

https://www.pc-freak.net/blog/changing-setting-33-times-standard-fsck-file-system-check-debian-linux-desktop-systems/
https://www.cyberciti.biz/faq/linux-force-fsck-on-the-next-reboot-or-boot-sequence/
https://www.cyberciti.biz/faq/linux-unix-bypassing-fsck/

Copyright © Linux教程網 All Rights Reserved