int nm_inotify_helper_add_watch (NMInotifyHelper *self, const char *path) { NMInotifyHelperPrivate *priv = NM_INOTIFY_HELPER_GET_PRIVATE (self); int wd; guint32 refcount; g_return_val_if_fail (priv->ifd >= 0, -1); /* We only care about modifications since we're just trying to get change * notifications on hardlinks. */ wd = inotify_add_watch (priv->ifd, path, IN_CLOSE_WRITE); if (wd < 0) return -1; refcount = GPOINTER_TO_UINT (g_hash_table_lookup (priv->wd_refs, GINT_TO_POINTER (wd))); refcount++; g_hash_table_replace (priv->wd_refs, GINT_TO_POINTER (wd), GUINT_TO_POINTER (refcount)); return wd; }
void udev_watch_begin(struct udev *udev, struct udev_device *dev) { char filename[UTIL_PATH_SIZE]; int wd; if (inotify_fd < 0) return; log_debug("adding watch on '%s'\n", udev_device_get_devnode(dev)); wd = inotify_add_watch(inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE); if (wd < 0) { log_error("inotify_add_watch(%d, %s, %o) failed: %m\n", inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE); return; } snprintf(filename, sizeof(filename), "/run/udev/watch/%d", wd); mkdir_parents(filename, 0755); unlink(filename); symlink(udev_device_get_id_filename(dev), filename); udev_device_set_watch_handle(dev, wd); }
static gboolean setup_file_watcher () { if ((inotify_fd = inotify_init ()) < 0) goto failed; if ((inotify_wd = inotify_add_watch (inotify_fd, SESSION_BUS_ADDRESS_FILENAME, IN_MODIFY | IN_ATTRIB | IN_DELETE_SELF)) < 0) goto failed; if ((inotify_channel = g_io_channel_unix_new (inotify_fd)) == NULL) goto failed; if ((inotify_source = g_io_add_watch (inotify_channel, G_IO_IN | G_IO_PRI, inotify_watch, NULL)) == 0) goto failed; return TRUE; failed: close_file_watcher (); return FALSE; }
void lutro_live_init() { memset(&live, 0, sizeof(live)); live.ifd = inotify_init1(IN_NONBLOCK); if (live.ifd < 0) { perror("Failed to initialize inotify"); lutro_live_deinit(); return; } // XXX: Some editors do not trigger IN_MODIFY since they write to a temp file // and rename() it to the actual file. live.wfd = inotify_add_watch(live.ifd, settings.gamedir, IN_MODIFY|IN_MOVED_TO); if (live.wfd < 0) { perror("Failed to monitor game directory"); lutro_live_deinit(); return; } }
int main(int argc, char * argv[]) { int fd; struct inotify_event * event; event = malloc(sizeof(struct inotify_event) + PATH_MAX); if (argc != 2) { fprintf(stderr, "usage: %s repertoire\n", argv[0]); exit(EXIT_FAILURE); } if ((fd = inotify_init()) < 0) { perror("inotify_init"); exit(EXIT_FAILURE); } if (inotify_add_watch(fd, argv[1], IN_ALL_EVENTS) < 0) { perror(argv[1]); exit(EXIT_FAILURE); } while (read(fd, event, sizeof(struct inotify_event) + PATH_MAX) > 0) { affiche_evenement(event); } return EXIT_SUCCESS; }
static int handle_add_watch(lua_State *L) { int fd; int wd; int top; int i; const char *path; uint32_t mask = 0; fd = get_inotify_handle(L, 1); path = luaL_checkstring(L, 2); top = lua_gettop(L); for(i = 3; i <= top; i++) { mask |= luaL_checkinteger(L, i); } if((wd = inotify_add_watch(fd, path, mask)) == -1) { return handle_error(L); } else { lua_pushinteger(L, wd); return 1; } }
bool EmulatedCameraHotplugThread::addWatch(int cameraId) { String8 camPath = getFilePath(cameraId); int wd = inotify_add_watch(mInotifyFd, camPath.string(), IN_CLOSE_WRITE); if (wd == -1) { ALOGE("%s: Could not add watch for '%s', error: '%s' (%d)", __FUNCTION__, camPath.string(), strerror(errno), errno); mRunning = false; return false; } ALOGV("%s: Watch added for camID='%d', wd='%d'", __FUNCTION__, cameraId, wd); SubscriberInfo si = { cameraId, wd }; mSubscribers.push_back(si); return true; }
void udev_watch_begin(struct udev *udev, struct udev_device *dev) { char filename[UTIL_PATH_SIZE]; int wd; if (inotify_fd < 0) return; info(udev, "adding watch on '%s'\n", udev_device_get_devnode(dev)); wd = inotify_add_watch(inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE); if (wd < 0) { err(udev, "inotify_add_watch(%d, %s, %o) failed: %m\n", inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE); return; } snprintf(filename, sizeof(filename), "%s/watch/%d", udev_get_run_path(udev), wd); util_create_path(udev, filename); unlink(filename); symlink(udev_device_get_id_filename(dev), filename); udev_device_set_watch_handle(dev, wd); }
static int monitor_add_directory_visitor( const dir_info *visit, void *data ) { if ( S_ISDIR(visit->mode) && strcmp(visit->name,".") && strcmp(visit->name,"..")) { monitor_t *m = (monitor_t *)data; int wd = inotify_add_watch(m->fd,visit->path,IN_CREATE | IN_DELETE | IN_CLOSE_WRITE | IN_MOVED_TO | IN_MOVED_FROM); if ( wd > 0 || errno == ENOSPC ) { log_debug(wd>0?"Added watch for %s":"Pending adding watch for when inotify resource available %s",visit->path);// if ( m->wd_lut_count >= m->wd_lut_size) { m->wd_lut_size *= 2; // need more space in buffer - double it m->wd_lut = realloc(m->wd_lut,m->wd_lut_size*sizeof(wd_t)); if ( !m->wd_lut ) return -1; // error allocating } m->wd_lut[m->wd_lut_count].wd = wd; m->wd_lut[m->wd_lut_count++].path = strdup(visit->path); qsort(m->wd_lut,m->wd_lut_count,sizeof(wd_t),wd_t_compare); // keep wd list sorted } else { log_debug("Failed adding watch for directory %s",visit->path); return -1; // unrecoverable error registering } } return 0; }
int open_inotify(void) { int fd; if ((fd = inotify_init1(IN_CLOEXEC|IN_NONBLOCK)) < 0) { log_error("Failed to create inotify handle: %m"); return -errno; } #ifdef ANDROID mkdir(READAHEAD_DIR, 0755); #else mkdir("/run/systemd", 0755); mkdir("/run/systemd/readahead", 0755); #endif if (inotify_add_watch(fd, READAHEAD_DIR, IN_CREATE) < 0) { log_error("Failed to watch /run/systemd/readahead: %m"); close_nointr_nofail(fd); return -errno; } return fd; }
static void watchdir_new_impl (dtr_watchdir * w) { int i; tr_sys_dir_t odir; w->inotify_fd = inotify_init (); if (w->inotify_fd < 0) { i = -1; } else { tr_logAddInfo ("Using inotify to watch directory \"%s\"", w->dir); i = inotify_add_watch (w->inotify_fd, w->dir, DTR_INOTIFY_MASK); } if (i < 0) { tr_logAddError ("Unable to watch \"%s\": %s", w->dir, tr_strerror (errno)); } else if ((odir = tr_sys_dir_open (w->dir, NULL)) != TR_BAD_SYS_DIR) { const char * name; while ((name = tr_sys_dir_read_name (odir, NULL)) != NULL) { if (!tr_str_has_suffix (name, ".torrent")) /* skip non-torrents */ continue; tr_logAddInfo ("Found new .torrent file \"%s\" in watchdir \"%s\"", name, w->dir); w->callback (w->session, w->dir, name); } tr_sys_dir_close (odir, NULL); } }
LIST_NODE *add_to_watch_list(char *path, bool is_link) { /* Append directory to watchlist */ int wd = inotify_add_watch(fd, path, mask); /** * Check limit in: * proc/sys/fs/inotify/max_user_watches */ if (wd == -1) { printf("AN ERROR OCCURRED WHILE ADDING PATH %s:\n", path); printf("Please, take in consideration these possibilities:\n"); printf(" - Max user's watches reached! See /proc/sys/fs/inotify/max_user_watches\n"); printf(" - Resource is no more available!?\n"); printf(" - An infinite loop generated by cyclic symbolic link?\n"); return NULL; } WD_DATA *wd_data = malloc(sizeof(WD_DATA)); wd_data->wd = wd; wd_data->path = path; wd_data->symbolic_link = is_link; wd_data->links = list_init(); LIST_NODE *list_node = list_push(list_wd, (void *) wd_data); /* Log Message */ if (be_verbose || be_syslog) { char *message = malloc(sizeof(char) * MAXPATHLEN); sprintf(message, "WATCHING: (fd:%d,wd:%d)\t\t%s", fd, wd_data->wd, path); log_message(message); } return list_node; }
bool FileSystemWatcher::watch(const Path &p) { if (p.isEmpty()) return false; Path path = p; assert(!path.isEmpty()); std::lock_guard<std::mutex> lock(mMutex); const Path::Type type = path.type(); uint32_t flags = 0; switch (type) { case Path::File: flags = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_DELETE|IN_CLOSE_WRITE; break; case Path::Directory: flags = IN_MOVED_FROM|IN_MOVED_TO|IN_CREATE|IN_DELETE|IN_DELETE_SELF|IN_ATTRIB|IN_CLOSE_WRITE; if (!path.endsWith('/')) path.append('/'); break; default: error("FileSystemWatcher::watch() '%s' doesn't seem to be watchable", path.constData()); return false; } if (mWatchedByPath.contains(path)) { return false; } const int ret = inotify_add_watch(mFd, path.nullTerminated(), flags); if (ret == -1) { error("FileSystemWatcher::watch() watch failed for '%s' (%d) %s", path.constData(), errno, Rct::strerror().constData()); return false; } mWatchedByPath[path] = ret; mWatchedById[ret] = path; return true; }
static int evdev_inotify_init(void) { int ret; int fd; fd = inotify_init(); if (fd < 0) { logmsg(LOG_ERR, "Failed to initialize inotify: %s", strerror(errno)); return -1; } ret = inotify_add_watch(fd, EVDEV_DIR, IN_CREATE | IN_ONLYDIR); if (ret < 0) { logmsg(LOG_ERR, "Failed to add inotify watch for %s: %s", EVDEV_DIR, strerror(errno)); close(fd); fd = -1; return -1; } ret = evloop_add(fd, EPOLLIN, evdev_inotify_process); if (ret < 0) { logmsg(LOG_ERR, "Failed to add inotify fd to event loop"); close(fd); return -1; } return 0; }
//-------- WatchID FileWatcherLinux::addWatch(const String& directory, FileWatchListener* watcher, bool recursive) { int wd = inotify_add_watch (mFD, directory.c_str(), IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_MOVED_FROM | IN_DELETE); if (wd < 0) { if(errno == ENOENT) throw FileNotFoundException(directory); else throw Exception(strerror(errno)); // fprintf (stderr, "Error: %s\n", strerror(errno)); // return -1; } WatchStruct* pWatch = new WatchStruct(); pWatch->mListener = watcher; pWatch->mWatchID = wd; pWatch->mDirName = directory; mWatches.insert(std::make_pair(wd, pWatch)); return wd; }
//---------------------------------------------------------------------------- // call it after all watched files in the dir were added int dir_watcher_t::dir_watcher_init(ev_loop_t *loop) { // init the dir watcher fd_inotify_ = inotify_init1(IN_NONBLOCK); if( fd_inotify_ < 0 ) { return INOT_INIT_ERR; } int i_mask = IN_ALL_EVENTS; fd_iwatch_ = inotify_add_watch(fd_inotify_, dir_name_.c_str(), i_mask ); if( fd_iwatch_ < 0 ) { close(fd_inotify_); fd_inotify_ = -1; return INOT_ADD_WATCH_ERR; } p_loop_ = loop; // init libev io event showing that inotify device data are ready ev_io_init(&ev_w_inotify_, inotify_cb, fd_inotify_, EV_READ); // ev_set_priority (&inotify_watcher, EV_MAXPRI); ev_io_start (p_loop_, &ev_w_inotify_); // init timeout ev_timer_init(&ev_w_dir_timeout_, dir_timeout_cb, 0.0, d_dir_timeout_sec_); ev_timer_again( p_loop_, &ev_w_dir_timeout_); // init all file watchers for( int i=0; i< watched_files_.size(); i++) { watched_files_[i]->file_watcher_init(p_loop_); } return 0; }
/* Set up an inotify watch on /dev/input. */ void open_inotify(void) { int fd = -1; int wd = -1; struct connection c; /* set up inotify */ fd = inotify_init1(IN_CLOEXEC); if (fd < 0) { acpid_log(LOG_ERR, "inotify_init() failed: %s (%d)", strerror(errno), errno); return; } acpid_log(LOG_DEBUG, "inotify fd: %d", fd); /* watch for files being created or deleted in /dev/input */ wd = inotify_add_watch(fd, ACPID_INPUTLAYERDIR, IN_CREATE | IN_DELETE); if (wd < 0) { acpid_log(LOG_ERR, "inotify_add_watch() failed: %s (%d)", strerror(errno), errno); close(fd); return; } acpid_log(LOG_DEBUG, "inotify wd: %d", wd); /* add a connection to the list */ c.fd = fd; c.process = process_inotify; c.pathname = NULL; c.kybd = 0; add_connection(&c); }
void JoystickImpl::initialize() { // Reset the array of plugged joysticks std::fill(plugged, plugged + Joystick::Count, false); // Create the inotify instance notifyFd = inotify_init(); if (notifyFd < 0) { err() << "Failed to initialize inotify, joystick connections and disconnections won't be notified" << std::endl; return; } // Watch nodes created and deleted in the /dev/input directory inputFd = inotify_add_watch(notifyFd, "/dev/input", IN_CREATE | IN_DELETE); if (inputFd < 0) { err() << "Failed to initialize inotify, joystick connections and disconnections won't be notified" << std::endl; return; } // Do an initial scan updatePluggedList(); }
gint32 _ik_watch (const char *path, guint32 mask, int *err) { gint32 wd = -1; g_assert (path != NULL); g_assert (inotify_instance_fd >= 0); wd = inotify_add_watch (inotify_instance_fd, path, mask); if (wd < 0) { int e = errno; /* FIXME: debug msg failed to add watch */ if (err) *err = e; return wd; } g_assert (wd >= 0); return wd; }
static inline int xmsg_add_watch(session_t *s, const char *f) { struct stat fs; const char *dir = xmsg_dirfix(f); if (!dir) return 0; else if (!stat(dir, &fs)) { if (!S_ISDIR(fs.st_mode)) xerr("given path is a file, not a directory"); } else { if (mkdir(dir, 0777)) xerrn("mkdir failed"); } #ifdef HAVE_INOTIFY if ((s->priv = (void*) (long int) inotify_add_watch(in_fd, dir, (IN_CLOSE_WRITE|IN_MOVED_TO|IN_ONLYDIR))) == (void*) -1) xerrn("unable to add inotify watch"); xdebug("inotify watch added: %d", (long int) s->priv); #endif /*HAVE_INOTIFY*/ return 0; }
int add_watch(int fd, const char * path) { struct watch *nw; int wd; wd = inotify_add_watch(fd, path, IN_CREATE|IN_CLOSE_WRITE|IN_DELETE|IN_MOVE); if( wd < 0 ) { DPRINTF(E_ERROR, L_INOTIFY, "inotify_add_watch(%s) [%s]\n", path, strerror(errno)); return -1; } nw = malloc(sizeof(struct watch)); if( nw == NULL ) { DPRINTF(E_ERROR, L_INOTIFY, "malloc() error\n"); return -1; } nw->wd = wd; nw->next = NULL; nw->path = strdup(path); if( watches == NULL ) { watches = nw; } if( lastwatch != NULL ) { lastwatch->next = nw; } lastwatch = nw; return wd; }
/* Initialize a parent watch entry. */ static struct audit_parent *audit_init_parent(struct nameidata *ndp) { struct audit_parent *parent; s32 wd; parent = kzalloc(sizeof(*parent), GFP_KERNEL); if (unlikely(!parent)) return ERR_PTR(-ENOMEM); INIT_LIST_HEAD(&parent->watches); parent->flags = 0; inotify_init_watch(&parent->wdata); /* grab a ref so inotify watch hangs around until we take audit_filter_mutex */ get_inotify_watch(&parent->wdata); wd = inotify_add_watch(audit_ih, &parent->wdata, ndp->dentry->d_inode, AUDIT_IN_WATCH); if (wd < 0) { audit_free_parent(&parent->wdata); return ERR_PTR(wd); } return parent; }
int ldcs_notify_init(char *path) { int fd=-1; fd=nt_get_new_fd(); if(fd<0) return(-1); ldcs_fdlist_nt[fd].inuse= 1; ldcs_fdlist_nt[fd].ntfd = inotify_init(); if (ldcs_fdlist_nt[fd].ntfd < 0) { _error("failure while running inotify_init"); } debug_printf3("add watch: ntfd=%d dir=%s\n",ldcs_fdlist_nt[fd].ntfd, path); ldcs_fdlist_nt[fd].wd = inotify_add_watch(ldcs_fdlist_nt[fd].ntfd, path, IN_CREATE); if (ldcs_fdlist_nt[fd].wd < 0) { _error ("inotify_add_watch"); } ldcs_fdlist_nt[fd].buffer_len=BUF_LEN; ldcs_fdlist_nt[fd].buffer=malloc(ldcs_fdlist_nt[fd].buffer_len); ldcs_fdlist_nt[fd].buffer_next=-1; /* nothing read */ return(fd); }
static void * hc_thread(void *data) { int fd = inotify_init(); HCDirEntry *dirs; int len; HCFileData *fl = NULL; char buffer[INOTIFY_BUFLEN]; struct timeval last_free, now; gettimeofday(&last_free, NULL); /* Setup watchers for the directories, these are a one time setup */ dirs = setup_watchers(fd); while (1) { int i = 0; /* First clean out anything old from the freelist */ gettimeofday(&now, NULL); if ((now.tv_sec - last_free.tv_sec) > FREELIST_TIMEOUT) { HCFileData *fdata = fl, *prev_fdata = fl; TSDebug(PLUGIN_NAME, "Checking the freelist"); memcpy(&last_free, &now, sizeof(struct timeval)); while(fdata) { if (fdata->remove > now.tv_sec) { if (prev_fdata) prev_fdata->_next = fdata->_next; fdata = fdata->_next; TSDebug(PLUGIN_NAME, "Cleaning up entry from frelist"); TSfree(fdata); } else { prev_fdata = fdata; fdata = fdata->_next; } } } /* Read the inotify events, blocking! */ len = read(fd, buffer, INOTIFY_BUFLEN); if (len >= 0) { while (i < len) { struct inotify_event *event = (struct inotify_event *)&buffer[i]; int wd = event->wd; HCFileInfo *finfo = g_config; while (finfo) { if ((wd == finfo->wd) || (wd == finfo->dir->wd && !strncmp(event->name, finfo->basename, event->len))) break; finfo = finfo->_next; } if (finfo) { HCFileData *new_data = TSmalloc(sizeof(HCFileData)); if (event->mask & (IN_CLOSE_WRITE)) { TSDebug(PLUGIN_NAME, "Modify file event (%d) on %s", event->mask, finfo->fname); } else if (event->mask & (IN_CREATE|IN_MOVED_TO)) { TSDebug(PLUGIN_NAME, "Create file event (%d) on %s", event->mask, finfo->fname); finfo->wd = inotify_add_watch(fd, finfo->fname, IN_DELETE_SELF|IN_CLOSE_WRITE|IN_ATTRIB); } else if (event->mask & (IN_DELETE_SELF|IN_MOVED_FROM)) { TSDebug(PLUGIN_NAME, "Delete file event (%d) on %s", event->mask, finfo->fname); finfo->wd = inotify_rm_watch(fd, finfo->wd); } memset(new_data, 0, sizeof(HCFileData)); reload_status_file(finfo, new_data); finfo->data->_next = fl; finfo->data->remove = now.tv_sec + FREELIST_TIMEOUT; fl = finfo->data; ink_atomic_swap_ptr(&(finfo->data), new_data); } i += sizeof(struct inotify_event) + event->len; } } } /* Cleanup, in case we later exit this thread ... */ while (dirs) { HCDirEntry *d = dirs; dirs = dirs->_next; TSfree(d); } return NULL; /* Yeah, that never happens */ }
int acquire_terminal( const char *name, bool fail, bool force, bool ignore_tiocstty_eperm, usec_t timeout) { int fd = -1, notify = -1, r = 0, wd = -1; usec_t ts = 0; assert(name); /* We use inotify to be notified when the tty is closed. We * create the watch before checking if we can actually acquire * it, so that we don't lose any event. * * Note: strictly speaking this actually watches for the * device being closed, it does *not* really watch whether a * tty loses its controlling process. However, unless some * rogue process uses TIOCNOTTY on /dev/tty *after* closing * its tty otherwise this will not become a problem. As long * as the administrator makes sure not configure any service * on the same tty as an untrusted user this should not be a * problem. (Which he probably should not do anyway.) */ if (timeout != USEC_INFINITY) ts = now(CLOCK_MONOTONIC); if (!fail && !force) { notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0)); if (notify < 0) { r = -errno; goto fail; } wd = inotify_add_watch(notify, name, IN_CLOSE); if (wd < 0) { r = -errno; goto fail; } } for (;;) { struct sigaction sa_old, sa_new = { .sa_handler = SIG_IGN, .sa_flags = SA_RESTART, }; if (notify >= 0) { r = flush_fd(notify); if (r < 0) goto fail; } /* We pass here O_NOCTTY only so that we can check the return * value TIOCSCTTY and have a reliable way to figure out if we * successfully became the controlling process of the tty */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC); if (fd < 0) return fd; /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed * if we already own the tty. */ assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0); /* First, try to get the tty */ if (ioctl(fd, TIOCSCTTY, force) < 0) r = -errno; assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0); /* Sometimes it makes sense to ignore TIOCSCTTY * returning EPERM, i.e. when very likely we already * are have this controlling terminal. */ if (r < 0 && r == -EPERM && ignore_tiocstty_eperm) r = 0; if (r < 0 && (force || fail || r != -EPERM)) goto fail; if (r >= 0) break; assert(!fail); assert(!force); assert(notify >= 0); for (;;) { union inotify_event_buffer buffer; struct inotify_event *e; ssize_t l; if (timeout != USEC_INFINITY) { usec_t n; n = now(CLOCK_MONOTONIC); if (ts + timeout < n) { r = -ETIMEDOUT; goto fail; } r = fd_wait_for_event(fd, POLLIN, ts + timeout - n); if (r < 0) goto fail; if (r == 0) { r = -ETIMEDOUT; goto fail; } } l = read(notify, &buffer, sizeof(buffer)); if (l < 0) { if (errno == EINTR || errno == EAGAIN) continue; r = -errno; goto fail; } FOREACH_INOTIFY_EVENT(e, buffer, l) { if (e->wd != wd || !(e->mask & IN_CLOSE)) { r = -EIO; goto fail; } } break; } /* We close the tty fd here since if the old session * ended our handle will be dead. It's important that * we do this after sleeping, so that we don't enter * an endless loop. */ fd = safe_close(fd); } safe_close(notify); r = reset_terminal_fd(fd, true); if (r < 0) log_warning_errno(r, "Failed to reset terminal: %m"); return fd; fail: safe_close(fd); safe_close(notify); return r; }
static int add_watch(struct filter *filt, struct knote *kn) { struct epoll_event ev; int ifd; char path[PATH_MAX]; uint32_t mask; /* Convert the fd to a pathname */ if (linux_fd_to_path(&path[0], sizeof(path), kn->kev.ident) < 0) return (-1); /* Convert the fflags to the inotify mask */ mask = IN_CLOSE; if (kn->kev.fflags & NOTE_DELETE) mask |= IN_ATTRIB | IN_DELETE_SELF; if (kn->kev.fflags & NOTE_WRITE) mask |= IN_MODIFY | IN_ATTRIB; if (kn->kev.fflags & NOTE_EXTEND) mask |= IN_MODIFY | IN_ATTRIB; if ((kn->kev.fflags & NOTE_ATTRIB) || (kn->kev.fflags & NOTE_LINK)) mask |= IN_ATTRIB; if (kn->kev.fflags & NOTE_RENAME) mask |= IN_MOVE_SELF; if (kn->kev.flags & EV_ONESHOT) mask |= IN_ONESHOT; /* Create an inotify descriptor */ ifd = inotify_init(); if (ifd < 0) { dbg_perror("inotify_init(2)"); return (-1); } /* Add the watch */ dbg_printf("inotify_add_watch(2); inofd=%d, %s, path=%s", ifd, inotify_mask_dump(mask), path); kn->kev.data = inotify_add_watch(ifd, path, mask); if (kn->kev.data < 0) { dbg_perror("inotify_add_watch(2)"); goto errout; } /* Add the inotify fd to the epoll set */ memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.ptr = kn; if (epoll_ctl(filter_epfd(filt), EPOLL_CTL_ADD, ifd, &ev) < 0) { dbg_perror("epoll_ctl(2)"); goto errout; } kn->kdata.kn_inotifyfd = ifd; return (0); errout: kn->kdata.kn_inotifyfd = -1; (void) close(ifd); return (-1); }
} #endif // IN_ONLYDIR } void InotifyEvent::DumpTypes(std::string& rStr) const { DumpTypes(m_uMask, rStr); } void InotifyWatch::SetMask(uint32_t uMask) throw (InotifyException) { IN_WRITE_BEGIN if (m_wd != -1) { int wd = inotify_add_watch(m_pInotify->GetDescriptor(), m_path.c_str(), uMask); if (wd != m_wd) { IN_WRITE_END_NOTHROW throw InotifyException(IN_EXC_MSG("changing mask failed"), wd == -1 ? errno : EINVAL, this); } } m_uMask = uMask; IN_WRITE_END } void InotifyWatch::SetEnabled(bool fEnabled) throw (InotifyException) { IN_WRITE_BEGIN
static void setup(void) { plugin.io.fd = inotify_init1(IN_NONBLOCK); if (-1 == plugin.io.fd || inotify_add_watch(plugin.io.fd, "/dev", IN_CREATE | IN_DELETE) < 0) _e("Failed starting TTY watcher: %s", strerror(errno)); }
void *watch_share() { int length, i = 0, wd; int fd; int rc; int access_count = 1; int r_count = 1; char *p; char buffer[BUF_LEN] __attribute__ ((aligned(8))); int counter = 0; int wds[MAX_WTD]; String dirs[MAX_WTD]; String query; sqlite3 *db; sqlite3_stmt *res; const char *tail; rc = sqlite3_open(DBNAME, &db); if (rc != SQLITE_OK){ fprintf(stderr, "Can't open database: %s.\n", sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } strcpy(query, "SELECT mountpt FROM Target;"); rc = sqlite3_prepare_v2(db, query, 1000, &res, &tail); if (rc != SQLITE_OK){ fprintf(stderr, "Failed to retrieved data.\n"); exit(1); } /*Initialize inotify*/ fd = inotify_init(); if ( fd < 0 ) { perror( "Couldn't initialize inotify" ); } list_dir(TEMP_LOC, fd, wds, dirs, counter); //printf("HELLO!!!\n"); while (sqlite3_step(res) == SQLITE_ROW){ wd = inotify_add_watch(fd, sqlite3_column_text(res,0), IN_CREATE | IN_OPEN | IN_CLOSE); wds[counter] = wd; strcpy(dirs[counter], sqlite3_column_text(res,0)); counter++; if (wd == -1){ syslog(LOG_INFO, "FileTransaction: Couldn't add watch to %s\n", sqlite3_column_text(res,0)); } else { syslog(LOG_INFO, "FileTransaction: Watching:: %s\n", sqlite3_column_text(res,0)); } //Check each target for directory String dir_to_read = ""; strcpy(dir_to_read, sqlite3_column_text(res,0)); list_dir(dir_to_read, fd, wds, dirs, counter); } wd = inotify_add_watch(fd, CACHE_LOC, IN_OPEN | IN_CLOSE); wds[counter] = wd; strcpy(dirs[counter], CACHE_LOC); counter++; if (wd != -1){ syslog(LOG_INFO, "FileTransaction: Watching:: %s\n", CACHE_LOC); } /*do it forever*/ for(;;){ create_link(); length = read(fd, buffer, BUF_LEN); if (length < 0){ perror("read"); } for(p = buffer; p < buffer + length;){ struct inotify_event *event = (struct inotify_event *) p; if (event->mask & IN_CREATE){ if (event->mask & IN_ISDIR){ int size = sizeof(wds) / sizeof(wds[0]); int i = 0; for (i = 0; i < size; i++){ if (wds[i] == event->wd){ if (strstr(dirs[i], "/mnt/Share") == NULL){ String add_watch_dir = ""; sprintf(add_watch_dir, "%s/%s", dirs[i], event->name); int wd = inotify_add_watch(fd, add_watch_dir, IN_ALL_EVENTS); if (wd == -1){ } else { printf("READ := Watching := %s\n", add_watch_dir); } wds[counter] = wd; strcpy(dirs[counter], add_watch_dir); counter++; } break; } } } else { } } if (event->mask & IN_OPEN){ if (event->mask & IN_ISDIR){ }else { //printf("Linear file %s opened.\n", event->name); if (strstr(event->name,"part1.") != NULL){ int k = 0; for (k = 0; k < counter; k++){ if (wds[k] == event->wd){ //printf("IN OPEN : %s | FILENAME : %s\n", dirs[k], event->name); break; } } //printf("FILENAME : %s opened.\n", event->name); int flag; FILE *fp = fopen("random.txt", "r"); fscanf(fp,"%d",&flag); fclose(fp); printf("IN OPEN FLAG := %d\n", flag); if (flag == 0){ //done striping continue with open event incrementFrequency(event->name); String comm = "", comm_out = ""; int inCache = 0; sprintf(comm, "ls %s", CACHE_LOC); runCommand(comm, comm_out); char *ptr = NULL; ptr = strtok(comm_out, "\n"); while (ptr != NULL){ if (strcmp(ptr, event->name) == 0){ inCache = 1; break; } ptr = strtok(NULL, "\n"); } if (!inCache){ printf("Watch Share: Should be assembling file here....\n"); FILE *fp1 = fopen("assembled.txt", "rb"); String file = ""; int check = 0; String line = ""; strcpy(file, event->name); strcat(file, "\n"); while (fgets(line, sizeof(file), fp1) != NULL){ printf("LINE := %s | FILENAME := %s\n", line, event->name); if (strcmp(line, file) == 0){ printf("SAME FILE := \n"); check = 1; break; } } fclose(fp1); if (!check){ // assemble the file by getting parts from volumes // take NOTE: assembly of file should only happen when all files are present // (or when no file striping is happening) // can this be determined with random.txt? assemble(event->name);} //String assembled_file = ""; //sprintf(assembled_file, "%s/%s", ASSEMBLY_LOC, event->name); //printf("Assembled File: %s\n", assembled_file); //assemble(event->name); //printf("Checking if assembled file exist...\n"); //FILE *fp; //fp = fopen(assembled_file, "r"); //if (fp == NULL){ //printf("Assembled file does not exist. Assembling here...\n"); //assemble(event->name); //} else { //printf("Assembled file already exist. Don't assembled anymore..\n"); //} //fclose(fp); } } } } } if (event->mask & IN_CLOSE){ if (event->mask & IN_ISDIR){ }else{ syslog(LOG_INFO, "FileTransaction: The file %s was closed.\n", event->name); //printf("File %s closed.\n", event->name); int k = 0; for (k = 0; k < counter; k++){ if (wds[k] == event->wd){ //printf("IN_CLOSE : %s | FILENAME : %s\n", dirs[k], event->name); break; } } //strcpy(COMMANDS[COUNTER], ""); //COUNTER++; //String original_file = ""; //sprintf(original_file, "%s/%s", STORAGE_LOC, event->name); //FILE *fp; // fp = fopen(original_file, "r"); // if (fp == NULL){ // printf("Original file does not exist.. Do nothing..\n"); // } else { // printf("Original file exist. File closed. Disassembling file..\n"); //} //fclose(fp); int flag; FILE *fp = fopen("random.txt", "rb"); fscanf(fp, "%d", &flag); fclose(fp); printf("IN CLOSE FLAG := %d\n", flag); if (flag == 0) { //done striping String comm = "", comm_out = ""; int inCache = 0; strcpy(comm, "ls /mnt/CVFSCache"); runCommand(comm, comm_out); char *pch = strtok(comm_out, "\n"); while (pch != NULL){ if (strcmp(pch, event->name) == 0){ inCache = 1; break; } pch = strtok(NULL, "\n"); } if (!inCache){ //check if file already assembled FILE *fp = fopen("assembled.txt", "rb"); String line = ""; String file = ""; int assembled = 0; strcpy(file, event->name); strcat(file, "\n"); while (fgets(line, sizeof(file), fp) != NULL){ printf("LINE := %s | FILE := %s\n", line, event->name); if (strcmp(line, file) == 0){ assembled = 1; break; } } fclose(fp); if (assembled){ printf("File has been closed\n"); disassemble(event->name); } } if (strstr(event->name, "part1.") != NULL){ refreshCache(); } } } } p += EVENT_SIZE + event->len; } } /* Clean up */ inotify_rm_watch(fd, wd); close(fd); sqlite3_finalize(res); sqlite3_close(db); }
static int update_notify_run_systemd_timesync(ClockState *sp) { sp->run_systemd_timesync_wd = inotify_add_watch(sp->inotify_fd, "/run/systemd/timesync", IN_CREATE|IN_DELETE_SELF); return sp->run_systemd_timesync_wd; }