# Inotify

> 高效、實時的Linux 文件系統事件監控框架

## 概要

**1. 爲什麼需要監控文件系統？**\
人們需要知道在某些文件（夾）上都有哪些變化，比如：

* 通知配置文件的改變
* 跟蹤某些關鍵的系統文件的變化
* 監控某個分區磁盤的整體使用情況
* 系統崩潰時進行自動清理
* 自動觸發備份進程
* 向服務器上傳文件結束時發出通知

通常使用文件輪詢的通知機制，但是這種機制只適用於經常改變的文件（因爲它可以確保每過x秒就可以得到i/o），其他情況下都非常低效，並且有時候會丟失某些類型的變化，例如文件的修改時間沒有改變。像 Tripwire這樣的數據完整性系統，他們基於時間調度來跟蹤文件變化，但是如果想實時監控的變化的話，那麼時間調度就束手無策了。Inotify 就這樣應運而生。

**2. Inotify到底是什麼?**\
Inotify是一種文件變化通知機制，Linux內核從2.6.13開始引入。在BSD和Mac OS系統中比較有名的是kqueue，它可以高效的實時跟蹤Linux文件系統的變化。近些年來，以fsnotify 作爲後端，幾乎所有的主流Linux發行版都支持Inotify 機制。如何知道你的Linux 內核是否支持Inotify機制呢

```
% grep INOTIFY_USER /boot/config-$(uname -r)
CONFIG_INOTIFY_USER=y
```

```
inotifywait -rme modify,attrib,move,close_write,create,delete,delete_self /srv/test
```

## 總結

綜上所述，Inotify爲Linux提供了一套高效監控和跟蹤文件變化機制，他可以實時的處理、調試以及監控文件變化，而輪詢是一種延遲機制。對於系統管理員，關於實現事件驅動的服務和系統備份，構建服務以及基於文件操作的程序調試等，inotify無疑提供了強大的支持。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://raozhanping.gitbook.io/notes/service-terminal/inotify.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
