1 /* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 #ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_WATCHER_FS_FILE_WATCHER_H 16 #define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_WATCHER_FS_FILE_WATCHER_H 17 18 #include <mutex> 19 #include <string> 20 #include <thread> 21 22 #include <sys/inotify.h> 23 24 #include "filemgmt_libfs.h" 25 #include "fs_watch_entity.h" 26 #include "singleton.h" 27 #include "watcher_data_cache.h" 28 29 namespace OHOS::FileManagement::ModuleFileIO { 30 using namespace std; 31 32 constexpr int32_t BUF_SIZE = 1024; 33 34 class FsFileWatcher : public Singleton<FsFileWatcher> { 35 public: 36 int32_t GetNotifyId(); 37 bool InitNotify(); 38 int32_t StartNotify(shared_ptr<WatcherInfo> info); 39 int32_t StopNotify(shared_ptr<WatcherInfo> info); 40 void GetNotifyEvent(); 41 void AsyncGetNotifyEvent(); 42 bool AddWatcherInfo(shared_ptr<WatcherInfo> info); 43 bool CheckEventValid(uint32_t event); 44 45 public: 46 FsFileWatcher() = default; 47 ~FsFileWatcher() = default; 48 FsFileWatcher(const FsFileWatcher &) = delete; 49 FsFileWatcher &operator=(const FsFileWatcher &) = delete; 50 51 private: 52 uint32_t RemoveWatcherInfo(shared_ptr<WatcherInfo> info); 53 void NotifyEvent(const struct inotify_event *event); 54 int32_t CloseNotifyFd(); 55 int32_t CloseNotifyFdLocked(); 56 int32_t NotifyToWatchNewEvents(const string &fileName, int32_t wd, uint32_t watchEvents); 57 void ReadNotifyEvent(); 58 void ReadNotifyEventLocked(); 59 void DestroyTaskThead(); 60 61 private: 62 static constexpr int32_t pollTimeoutMs = 500; 63 64 mutex taskMutex_; 65 mutex readMutex_; 66 67 atomic<bool> taskRunning_ = false; 68 thread taskThead_; 69 70 bool run_ = false; 71 bool reading_ = false; 72 bool closed_ = false; 73 int32_t notifyFd_ = -1; 74 int32_t eventFd_ = -1; 75 WatcherDataCache dataCache_; 76 }; 77 78 } // namespace OHOS::FileManagement::ModuleFileIO 79 #endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_WATCHER_FS_FILE_WATCHER_H 80