首頁  >  文章  >  後端開發  >  linux檔案資料夾遞歸監控

linux檔案資料夾遞歸監控

高洛峰
高洛峰原創
2016-11-02 10:47:101235瀏覽

linux檔案資料夾遞歸監控

開發了一個規範的php composer套件,使用的時候直接require即可。

實作

php版本的實作沿用了shell版本的思想,透過管道指令傳遞shell指令的結果,然後對結果做各種處理,達到我們監控檔案的目的。

為了完成這個功能,首先要實作一個php版本的管道指令,這裡我對resource popen ( string $command , string $mode )做了封裝,可以透過很友善的處理指令的回傳值。

完成了上面的模組,接下來就是具體的實現了,實現這裡有多重友好的方式,添加多路徑遞歸監控、包含正則匹配、排除正則匹配。

pipe的開發

<?php/** * php对对popen的封装,通过回调的方式模拟管道命令 * */namespace Aizuyan\Pipe;class Pipe{    /**     * 要通过管道执行的命令     */
    protected $command = "";
    /**     * 回调函数,将管道数据传递给该函数     */
    protected $callback = null;
    /**     * 数据之间的分隔符     */
    protected $delimiter = "\n";
    /**     * 设置命令     *     * @param cmd string 要运行的命令     */
    public function setCmd($cmd)
    {        $this->command = $cmd;
        return $this;
    }    /**     * 设置回调函数,处理管道输出的命令     */
    public function setCallback(callable $cb)
    {        $this->callback = $cb;
        return $this;
    }    /**     * 设置数据片段之间的分隔符     */
    public function setDelimiter($delimiter)
    {        $this->delimiter = $delimiter;
        return $this;
    }    /**     * 开始运行     */
    public function run()
    {        $fp = popen($this->command, "r");
        if (false === $fp) {            throw new \RuntimeException("popen execute command failed!");
        }        $item = "";
        while (!feof($fp)) {            $char = fgetc($fp);
            if ($this->delimiter == $char) {                call_user_func($this->callback, $item);
                $item = "";
            } else {                $item .= $char;
            }
        }        pclose($fp);
    }
}

下面是測試程序

include "vendor/autoload.php";
$test = new RitoyanPipePipe();
$test->setCmd("tail -f /root/t.txt ")->setCallback(function($item){
       echo "取得內容:" . $item . "n";
})->setDelimiter("n")->run();

對tail -f / root/t.txt這個shell指令的回傳結果進行即時處理,setCallback(callable func)設定了回呼函數,func的參數是shell指令的標準輸出,setDelimiter($delimiter)設定了傳入回呼函數參數的分隔符,這樣就可以很容易、很任性的將輸出傳遞給回呼函數了。

inotify開發

這部分程式碼就不提出來了,主要就是依賴上面的Pipe然後對inotifywait -mrq --format '%w,%e,%f'指令的輸出做處理,正向逆向過濾,下面是Inotify的呼叫

<?php
require "vendor/autoload.php";
$obj = new Aizuyan\Inotify\Inotify();
$obj->addExclude([
    "/swp$/",
    "/swpx$/",
    "/~$/",
    "/\d$/",
    "/swx$/"
])->setCallback(function ($item){
    echo $item["event"] . " 文件 " . $item["file"] . "\n";
})->addPaths("/datas/git/")->start();

這樣運作之後,到我們修改/datas/git目錄下的檔案的時候會輸出下面的內容,可以很方便的對修改檔案做客製化的處理

CREATE 文件 /datas/git/inotify/README.md
MODIFY 文件 /datas/git/inotify/README.md
MOVED_TO 文件 /datas/git/aizuyan/pinyin-1/README.md
DELETE 文件 /datas/git/aizuyan/pinyin-1/LICENSE
......

inotify-tools安裝

整個功能依賴於一個linux軟體—— inotify-tools
centos安裝yum install inotify-tools,或者透過原始碼直接安裝(文件)嘗試在OS中安裝,發現失敗了~

如何使用

我已經將他發佈到了composer倉庫中,可以輕鬆安裝:
composer require aizuyan/inotify,之後就可以像上面的例子一樣使用了

另外這是開發的兩個組件的github地址:Ai​​zuyanPipePipe , AizuyanInotifyInotuyanInot

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn