簡體   English   中英

Java捕獲Linux掛載/卸載文件夾

[英]Java catch linux mount / unmount for a folder

我有一個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();
            }
        }
    });
}

運行方法(實現為可運行):

/**
 * 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,最終導致線程終止。
從那時起,我真的不知道何時將再次安裝該文件夾-重新運行監視器線程。

監視文件夾安裝/卸載的最佳方法是什么?
請注意 :監視的端點文件夾不一定是安裝點,它(已安裝的文件夾)可能是其祖先之一。

任何幫助,將不勝感激!

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

不確定OpenSUSE,但我認為它們的工作方式與Redhat風格的linux相同。 https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html

在@StefanE答案之后,我發現了以下使用Java本機讀取此文件的好示例。
這個答案中
它很好地解析了/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM