cronが一定の時間ごとにジョブを実行させるためのものに対して、incronはファイルの変更などのイベント時に特定のジョブを実行させるもの。
Linuxのinotifyという仕組みを利用しており、Linuxカーネル2.6.13以降で使える。他のOSでは使えない。
incrontab
というコマンドでincronを管理し、cronを管理するcrontabとよく似ている。
sudo yum install incron
sudo apt-get install incron
このコマンドだけで、勝手に起動して、OS起動時の自動実行にも設定される。
(Ubuntu 12.04で確認)
incrontab
コマンドの使い方はcrontab
とよく似ている。
# ジョブの設定が書かれたファイルで設定incrontab ファイル名# ジョブの設定の一覧を表示incrontab -l# ジョブの設定をviなどで編集incrontab -e# ジョブの設定を削除incrontab -r
-r
はcrontab
と同じく、確認なしに設定を削除するので、要注意。
cronと同様に1行に1つのジョブを、スペース区切りで、監視対象ファイル、監視対象イベント、コマンドの順に書く。
例
/home/hoge/foo IN_CREATE,IN_DELETE /home/hoge/bin/script.sh $@/$# $%
監視対象ファイルはディレクトリも指定可能。パスにスペースが含まれる場合はバックスラッシュでエスケープする。
監視対象イベントは複数ある場合はカンマ(,
)区切りにする。
コマンドには以下の特殊なワイルドカードを使える。
$$
$@
$#
$%
$&
同じ監視対象ファイルに対して2つ以上設定しようとすると、syslogにDevice or resource busy
というエラーメッセージが記録されて、正しく設定できない。
コマンドの中にcronと同じ要領で>
を使ってファイルに出力しようとしてもできないみたい。[2013/05/12]
以下のコマンドで使用できるイベントの一覧を確認できる。(-t
というオプションはcrontab
にはなく、incrontab
特有)
incrontab -t
長い一行で見づらいので、
incrontab -t | sed -e 's/,/\n/g'
とでもする。各イベントの説明は、Linuxカーネルソースのinotify.h
に書いてある。
/* the following are legal, implemented events that user-space can watch for */#define IN_ACCESS0x00000001/* File was accessed */#define IN_MODIFY0x00000002/* File was modified */#define IN_ATTRIB0x00000004/* Metadata changed */#define IN_CLOSE_WRITE0x00000008/* Writtable file was closed */#define IN_CLOSE_NOWRITE0x00000010/* Unwrittable file closed */#define IN_OPEN0x00000020/* File was opened */#define IN_MOVED_FROM0x00000040/* File was moved from X */#define IN_MOVED_TO0x00000080/* File was moved to Y */#define IN_CREATE0x00000100/* Subfile was created */#define IN_DELETE0x00000200/* Subfile was deleted */#define IN_DELETE_SELF0x00000400/* Self was deleted */#define IN_MOVE_SELF0x00000800/* Self was moved *//* helper events */#define IN_CLOSE(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) /* close */#define IN_MOVE(IN_MOVED_FROM | IN_MOVED_TO) /* moves *//* special flags */#define IN_ONLYDIR0x01000000/* only watch the path if it is a directory */#define IN_DONT_FOLLOW0x02000000/* don't follow a sym link */#define IN_ONESHOT0x80000000/* only send event once *//* * All of the events - we build the list by hand so that we can add flags in * the future and not break backward compatibility. Apps will get only the * events that they originally wanted. Be sure to add new events here! */#define IN_ALL_EVENTS (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | \ IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM | \ IN_MOVED_TO | IN_DELETE | IN_CREATE | IN_DELETE_SELF | \ IN_MOVE_SELF)
man inotify
にもイベントの説明が書いてある。
実行されたコマンドのログは/var/log/syslog
に書きだされる(Ubuntuのデフォルトの設定で確認、他のOSでは違うかもしれない)。
他にLinuxで使える仕組みとして、fanotifyというものがあるらしい。
inotifyとfanotifyの比較
http://www.nminoru.jp/~nminoru/programming/file_change_notification.html