Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux tail -f 報錯「No space left on device」實為 inotify 監控上限不足

編輯:關於 Linux

執行 tail -f /var/log/catalina.out 卻報 tail: cannot watch '...': No space left on device,但 df -h、df -hi 均顯示空間充足。真相是:**tail -f 使用 inotify 監控檔案變更,預設每用戶監控上限 fs.inotify.max_user_watches = 8192 已耗盡**。

tail -f 報錯畫面

錯誤現象

# tail -f ../logs/catalina.out
tail: cannot watch '../logs/catalina.out': No space left on device

# df -h / df -hi 均有剩餘空間

根因

現代 tail -f(GNU coreutils 7.5+)預設使用 inotify 而非輪詢。每個被監控的檔案/目錄消耗一個 inotify watch。系統預設 fs.inotify.max_user_watches = 8192,大量服務(如 Java 應用、Docker 容器、監控 Agent)同時監控大量日誌檔案時極易耗盡。

解決方案:提高 inotify 監控上限

  1. 編輯 /etc/sysctl.conf:
    vim /etc/sysctl.conf
  2. 新增或修改:
    fs.inotify.max_user_watches = 524288
    (建議值 524288 = 512K,視記憶體大小調整;每 watch 約 1 KB 核心記憶體)
  3. 立即生效:
    sysctl -p /etc/sysctl.conf
  4. 驗證:
    tail ../logs/catalina.out 應正常輸出。

驗證當前用量

# 查看當前用戶已用 watches
find /proc/*/fd -lname 'anon_inode:inotify' -printf '%h\n' 2>/dev/null | xargs -I{} sh -c 'ls -l {}/* 2>/dev/null | grep -c inotify' | awk '{sum+=$1} END {print sum}'

# 或簡易估算:每個監控中的檔案/目錄約佔 1 watch
# 系統總上限
cat /proc/sys/fs/inotify/max_user_watches

替代方案(不調整參數)

  • 使用 tail --disable-inotify -f file 強制改用輪詢模式(較耗 CPU)。
  • less +F file 同樣可即時追蹤,不佔用 inotify watch。
  • 清理不必要的監控進程(如停用未用的 logstash/filebeat 配置)。

相關參數補充

參數預設值說明
fs.inotify.max_user_watches8192每用戶最大監控數(本文調整重點)
fs.inotify.max_user_instances128每用戶最大 inotify 實例數(每 inotify_init() 一個)
fs.inotify.max_queued_events16384佇列最大事件數,防爆佇列丟事件

調整 max_user_watches 後,tail -f、filebeat、docker 等依賴 inotify 的工具均受益,徹底解決「空間明明足卻報 No space left」的誤導性錯誤。

Copyright © Windows教程網 All Rights Reserved