Java为一个文件夹捕获linux mount / unmount

时间:2017-07-11 12:49:46

标签: java mount opensuse watchservice

我有一个java项目,其中一个组件是监视安装到我的机器上的特定文件夹 我的linux版本是OpenSUSE 42.1

用于监控我正在使用java Watch Service的文件夹 附件是我们在网上找到的文件夹监控的主要代码,并根据需要进行了修改 (抱歉没有版权,无法找到它的来源) 构造:

/**
 * Creates a WatchService and registers the given directory
 */
public WatchDir(Path dir, Kind<?>... dirWatchKinds) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<WatchKey,Path>();

    register(dir, dirWatchKinds);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                watcher.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}

运行方法(实现为runnable):

/**
 * Process all events for keys queued to the watcher
 */
public void run() {
    while (shouldRun) {

        // wait for key to be signalled
        WatchKey key;
        try {               
            key = watcher.take();
        } catch (Exception x) {             
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            log.error("WatchKey not recognized!!");
            continue;
        }

        for (WatchEvent<?> event: key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();

            if (kind == OVERFLOW) {
                continue;
            }

            // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

           handleDirEvent(child, ev.kind());

        }

        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            // Check that dir path still exists. If not, notify user and whoever run the thread
            if (Files.notExists(dir)){
                //log.error(String.format("Directory ", arg1));
                fireFileChangedEvent(dir.getFileName().toString(), FileState.Deleted);
            }

            keys.remove(key);

            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}

现在我的问题。
安装的文件夹很容易断开,这可能会在我的程序范围之外处理(从终端我猜) 目前,如果发生这种情况,watcher.take()会收到通知,无需处理任何事件, 并且在boolean valid = key.reset()上它获取值false,然后最终导致线程终止 从那时起,我真的不知道何时将再次安装该文件夹 - 用于重新运行监视器线程。

监控文件夹的安装/卸载的最佳方法是什么? 请注意:受监控的端点文件夹不一定是安装点,它(已安装的文件夹)可能是其祖先之一。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

您可以查看/proc/mounts文件以查看该安装是否仍然存在。

不确定OpenSUSE但我认为它们与Redhat样式linux的工作方式相同。 https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html

答案 1 :(得分:1)

在@StefanE回答之后,我找到了以下使用java native读取此文件的好例子 取自this answer
它很好地解析了/etc/mtab文件,并且根据我的具体用法,我会在每个时间间隔检查这个文件,看看文件夹是否再次安装。

    mntent mntEnt;
    Pointer stream = CLib.INSTANCE.setmntent("/etc/mtab", "r");
    while ((mntEnt = CLib.INSTANCE.getmntent(stream)) != null) {
        if (mntEnt.mnt_type.equalsIgnoreCase("cifs")){
            System.out.println("Mounted from: " + mntEnt.mnt_fsname);
            System.out.println("Mounted on: " + mntEnt.mnt_dir);
            System.out.println("File system type: " + mntEnt.mnt_type);
            System.out.println("-------------------------------");  
        }
    }

    CLib.INSTANCE.endmntent(stream);

我的具体用法是

Mounted from: //192.168.163.129/storage1/rawData
Mounted on: /mntMS/StorageServer1/rawData
File system type: cifs

Mounted from: //192.168.163.129/storage2/output
Mounted on: /mntMS/StorageServer2/output
File system type: cifs

Mounted from: //192.168.163.129/storage2/rawData
Mounted on: /mntMS/StorageServer2/rawData
File system type: cifs

Mounted from: //127.0.0.1/storage1/output
Mounted on: /mntMS/StorageServer1/output
File system type: cifs