示例#1
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *gerr = NULL;
	GIOChannel *inotify_io;
	struct stat sb;
	int err, retval = 0;
	int inotifyFD, wd;
	guint watch_id;

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	if (!g_option_context_parse(context, &argc, &argv, &gerr)) {
		g_printerr("Invalid arguments: %s\n", gerr->message);
		g_error_free(gerr);
		g_option_context_free(context);
		return EXIT_FAILURE;
	}

	g_option_context_free(context);

	if (stat(opt_cfg, &sb) == -1) {
		err = errno;
		g_printerr("%s: %s(%d)\n", opt_cfg, strerror(err), err);
		return EXIT_FAILURE;
	}

	if ((sb.st_mode & S_IFMT) != S_IFREG) {
		g_printerr("%s is not a regular file!\n", opt_cfg);
		return EXIT_FAILURE;
	}

	if (!opt_nodes) {
		g_printerr("Missing KNOT known nodes file!\n");
		return EXIT_FAILURE;
	}

	signal(SIGTERM, sig_term);
	signal(SIGINT, sig_term);
	signal(SIGPIPE, SIG_IGN);

	main_loop = g_main_loop_new(NULL, FALSE);

	hal_log_init("nrfd", opt_detach);
	hal_log_info("KNOT HAL nrfd");

	if (opt_host)
		hal_log_error("Development mode: %s:%u", opt_host, opt_port);

	err = manager_start(opt_cfg, opt_host, opt_port, opt_spi, opt_channel,
							opt_dbm, opt_nodes);
	if (err < 0) {
		hal_log_error("manager_start(): %s(%d)", strerror(-err), -err);
		g_main_loop_unref(main_loop);
		hal_log_close();
		return EXIT_FAILURE;
	}

	/* Set user id to nobody */
	if (setuid(65534) != 0) {
		err = errno;
		hal_log_error("Set uid to nobody failed. %s(%d). Exiting...",
							strerror(err), err);
		manager_stop();
		hal_log_close();
		return EXIT_FAILURE;
	}

	/* Starting inotify */
	inotifyFD = inotify_init();
	wd = inotify_add_watch(inotifyFD, opt_cfg, IN_MODIFY);
	if (wd == -1) {
		hal_log_error("Error adding watch on: %s", opt_cfg);
		close(inotifyFD);
		manager_stop();
		hal_log_close();
		return EXIT_FAILURE;
	}

	/* Setting gio channel to watch inotify fd*/
	inotify_io = g_io_channel_unix_new(inotifyFD);
	watch_id = g_io_add_watch(inotify_io, G_IO_IN, inotify_cb, NULL);
	g_io_channel_set_close_on_unref(inotify_io, TRUE);

	if (opt_detach) {
		if (daemon(0, 0)) {
			hal_log_error("Can't start daemon!");
			retval = EXIT_FAILURE;
			goto done;
		}
	}

	g_main_loop_run(main_loop);

done:
	g_source_remove(watch_id);
	inotify_rm_watch(inotifyFD, wd);
	g_io_channel_unref(inotify_io);

	manager_stop();

	hal_log_error("exiting ...");
	hal_log_close();

	g_main_loop_unref(main_loop);

	return retval;
}
void inotifyd_main(void)
{
  struct pollfd fds;
  char *prog_args[5], **ss = toys.optargs;
  char *masklist ="acew0rmyndDM uox";

  fds.events = POLLIN;

  *prog_args = *toys.optargs;
  prog_args[4] = 0;
  if ((fds.fd = inotify_init()) == -1) perror_exit(0);

  // Track number of watched files. First one was program to run.
  toys.optc--;

  while (*++ss) {
    char *path = *ss, *masks = strchr(*ss, ':');
    int i, mask = 0;

    if (!masks) mask = 0xfff; // default to all
    else{
      *masks++ = 0;
      for (*masks++ = 0; *masks; masks++) {
        i = stridx(masklist, *masks);;
        if (i == -1) error_exit("bad mask '%c'", *masks);
        mask |= 1<<i;
      }
    }

    // This returns increasing numbers starting from 1, which coincidentally
    // is the toys.optargs position of the file. (0 is program to run.)
    if (inotify_add_watch(fds.fd, path, mask) < 0) perror_exit_raw(path);
  }

  for (;;) {
    int ret = 0, len;
    void *buf = 0;
    struct inotify_event *event;

    // Read next event(s)
    ret = poll(&fds, 1, -1);
    if (ret < 0 && errno == EINTR) continue;
    if (ret <= 0) break;
    xioctl(fds.fd, FIONREAD, &len);
    event = buf = xmalloc(len);
    len = readall(fds.fd, buf, len);

    // Loop through set of events.
    for (;;) {
      int left = len - (((char *)event)-(char *)buf),
          size = sizeof(struct inotify_event);

      // Don't dereference event if ->len is off end of bufer
      if (left >= size) size += event->len;
      if (left < size) break;

      if (event->mask) {
        char *s = toybuf, *m;

        for (m = masklist; *m; m++)
          if (event->mask & (1<<(m-masklist))) *s++ = *m;
        *s = 0;

        if (**prog_args == '-' && !prog_args[0][1]) {
          xprintf("%s\t%s\t%s\n" + 3*!event->len, toybuf,
              toys.optargs[event->wd], event->name);
        } else {
          prog_args[1] = toybuf;
          prog_args[2] = toys.optargs[event->wd];
          prog_args[3] = event->len ? event->name : 0;
          xrun(prog_args);
        }

        if (event->mask & IN_IGNORED) {
          if (--toys.optc <= 0) {
            free(buf);

            goto done;
          }
          inotify_rm_watch(fds.fd, event->wd);
        }
      }
      event = (void*)(size + (char*)event);
    }
    free(buf);
  }

done:
  toys.exitval = !!toys.signal;
}
JNIEXPORT void JNICALL Java_com_mutter_uninstallmonitor_MainApp_forkUninstallMonitorProcess(
    JNIEnv *env, jobject object, jstring dirName, jstring intentUrl) {

    jboolean isCopy = true;
    const char* monitor_dir = env->GetStringUTFChars(dirName, &isCopy);
    const char* intent_url = env->GetStringUTFChars(intentUrl, &isCopy);
    LOGI("monitor directory %s\n", monitor_dir);
    LOGI("intent data uri %s\n", intent_url);

    pid_t pid;

    usleep(100);

    if ((pid = fork()) < 0) {
        LOGE("fork error");
    } else if (pid == 0) { /* first child */

        if ((pid = fork()) < 0) {
            LOGI("fork error");
        } else if (pid > 0) {
            exit(0);
        }

        // second child process
        setsid();
        char cwd[64] = { '0' };
        daemon(0, 0);
        getcwd(cwd, sizeof(cwd));
        LOGI("second child, pid = %d, cwd = %s\n", getpid(), cwd);

        int ret = -1;
        if ((ret = access(monitor_dir, F_OK | R_OK)) != 0) {
            LOGE("access error");
        }

        int length, i = 0;
        int fd;
        int wd;
        char buffer[EVENT_BUF_LEN];

        /* creating the INOTIFY instance */
        fd = inotify_init();

        if (fd < 0) {
            LOGE("inotify_init");
        }

        /**
         * add to watched list
         */
        wd = inotify_add_watch(fd, monitor_dir, IN_DELETE_SELF);
        LOGI("add to watched %s, fd = %d\n", monitor_dir, wd);

        /*
         * Read to determine the event change happen on data directory.
         * Actually this read blocks until the change event occurs
         */

        struct stat sb;
        if (stat(monitor_dir, &sb) == -1) {
            LOGE("stat");
        }

        if (S_ISDIR(sb.st_mode)) {
            LOGI("blocked on read call");
            length = read(fd, buffer, EVENT_BUF_LEN);

            if (length < 0) {
                LOGE("read");
            }
        } else {
            LOGI("blocked on if exists call");
            block_if_exists(dirname(dirname(monitor_dir)));
        }

        LOGI("monitor file %s removed\n", monitor_dir);

        // Permission Denial: getIntentSender()
        jclass cls = env->FindClass("com/mutter/uninstallmonitor/MainApp");
        jmethodID method = env->GetStaticMethodID(cls, "sendNotification", "()V");
        env->CallStaticVoidMethod(cls, method);
        LOGI("send notification");

        pid_t intent_pid;
        if ((intent_pid = fork()) < 0) {
            LOGE("fork error");
        } else if (intent_pid == 0) {
            LOGI("exec process");
            // Note: this won't work on Android 4.2 and up, which require the system level permission
            // android.permission.INTERACT_ACROSS_USERS_FULL
            const char* envp[5] = {
                "SHELL=/system/bin/sh",
                "PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin",
                "CLASSPATH=/system/framework/am.jar"
            };
            char bootclasspath[8192] = { '0' };
            sprintf(bootclasspath, "BOOTCLASSPATH=%s", getenv("BOOTCLASSPATH"));
            envp[3] = (const char*) bootclasspath;
            envp[4] = NULL;
            if (execle("/system/bin/app_process", "app_process",
                       "/system/bin", "com.android.commands.am.Am",
                       "start", "-a", "android.intent.action.VIEW",
                       "-d", intent_url,
                       "--activity-single-top", (char*) NULL, envp) == -1) {
                LOGI("execl error");
            } else {
                // this will never going to happen
                LOGI("execle successfully");
            }
        }
        inotify_rm_watch(fd, wd);

        // this work on Android 2.3.3, tested on HTC Desire
        // system("/system/bin/am start -a android.intent.action.VIEW -d http://www.baidu.com --activity-single-top");
        /* closing the INOTIFY instance */
        close(fd);
        exit(0);
    }

    //if (waitpid(pid, NULL, 0) != pid) {
    //	LOGI("wait error");
    //}
}
/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
const char *dump_traces() {
    const char* result = NULL;

    char traces_path[PROPERTY_VALUE_MAX] = "";
    property_get("dalvik.vm.stack-trace-file", traces_path, "");
    if (!traces_path[0]) return NULL;

    /* move the old traces.txt (if any) out of the way temporarily */
    char anr_traces_path[PATH_MAX];
    strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
    strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
    if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
        return NULL;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
    }

    /* make the directory if necessary */
    char anr_traces_dir[PATH_MAX];
    strlcpy(anr_traces_dir, traces_path, sizeof(anr_traces_dir));
    char *slash = strrchr(anr_traces_dir, '/');
    if (slash != NULL) {
        *slash = '\0';
        if (!mkdir(anr_traces_dir, 0775)) {
            chown(anr_traces_dir, AID_SYSTEM, AID_SYSTEM);
            chmod(anr_traces_dir, 0775);
        } else if (errno != EEXIST) {
            fprintf(stderr, "mkdir(%s): %s\n", anr_traces_dir, strerror(errno));
            return NULL;
        }
    }

    /* create a new, empty traces.txt file to receive stack dumps */
    int fd = open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW, 0666);  /* -rw-rw-rw- */
    if (fd < 0) {
        fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
        return NULL;
    }
    int chmod_ret = fchmod(fd, 0666);
    if (chmod_ret < 0) {
        fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
        close(fd);
        return NULL;
    }

    /* walk /proc and kill -QUIT all Dalvik processes */
    DIR *proc = opendir("/proc");
    if (proc == NULL) {
        fprintf(stderr, "/proc: %s\n", strerror(errno));
        goto error_close_fd;
    }

    /* use inotify to find when processes are done dumping */
    int ifd = inotify_init();
    if (ifd < 0) {
        fprintf(stderr, "inotify_init: %s\n", strerror(errno));
        goto error_close_fd;
    }

    int wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
    if (wfd < 0) {
        fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
        goto error_close_ifd;
    }

    struct dirent *d;
    int dalvik_found = 0;
    while ((d = readdir(proc))) {
        int pid = atoi(d->d_name);
        if (pid <= 0) continue;

        char path[PATH_MAX];
        char data[PATH_MAX];
        snprintf(path, sizeof(path), "/proc/%d/exe", pid);
        ssize_t len = readlink(path, data, sizeof(data) - 1);
        if (len <= 0) {
            continue;
        }
        data[len] = '\0';

        if (!strcmp(data, "/system/bin/app_process")) {
            /* skip zygote -- it won't dump its stack anyway */
            snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
            int fd = open(path, O_RDONLY);
            len = read(fd, data, sizeof(data) - 1);
            close(fd);
            if (len <= 0) {
                continue;
            }
            data[len] = '\0';
            if (!strcmp(data, "zygote")) {
                continue;
            }

            ++dalvik_found;
            if (kill(pid, SIGQUIT)) {
                fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
                continue;
            }

            /* wait for the writable-close notification from inotify */
            struct pollfd pfd = { ifd, POLLIN, 0 };
            int ret = poll(&pfd, 1, 200);  /* 200 msec timeout */
            if (ret < 0) {
                fprintf(stderr, "poll: %s\n", strerror(errno));
            } else if (ret == 0) {
                fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
            } else {
                struct inotify_event ie;
                read(ifd, &ie, sizeof(ie));
            }
        } else if (should_dump_native_traces(data)) {
            /* dump native process if appropriate */
            if (lseek(fd, 0, SEEK_END) < 0) {
                fprintf(stderr, "lseek: %s\n", strerror(errno));
            } else {
                dump_backtrace_to_file(pid, fd);
            }
        }
    }

    if (dalvik_found == 0) {
        fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
    }

    static char dump_traces_path[PATH_MAX];
    strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
    strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
    if (rename(traces_path, dump_traces_path)) {
        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
        goto error_close_ifd;
    }
    result = dump_traces_path;

    /* replace the saved [ANR] traces.txt file */
    rename(anr_traces_path, traces_path);

error_close_ifd:
    close(ifd);
error_close_fd:
    close(fd);
    return result;
}
示例#5
0
/**
 * xenInotifyOpen:
 * @conn: pointer to the connection block
 * @name: URL for the target, NULL for local
 * @flags: combination of virDrvOpenFlag(s)
 *
 * Connects and starts listening for inotify events
 *
 * Returns 0 or -1 in case of error.
 */
int
xenInotifyOpen(virConnectPtr conn,
               virConnectAuthPtr auth ATTRIBUTE_UNUSED,
               unsigned int flags)
{
    DIR *dh;
    struct dirent *ent;
    char *path;
    xenUnifiedPrivatePtr priv = conn->privateData;

    virCheckFlags(VIR_CONNECT_RO, -1);

    if (priv->configDir) {
        priv->useXenConfigCache = 1;
    } else {
        /* /var/lib/xend/domains/<uuid>/config.sxp */
        priv->configDir = XEND_DOMAINS_DIR;
        priv->useXenConfigCache = 0;

        if (VIR_ALLOC(priv->configInfoList) < 0)
            return -1;

        /* populate initial list */
        if (!(dh = opendir(priv->configDir))) {
            virReportSystemError(errno,
                                 _("cannot open directory: %s"),
                                 priv->configDir);
            return -1;
        }
        while ((ent = readdir(dh))) {
            if (STRPREFIX(ent->d_name, "."))
                continue;

            /* Build the full file path */
            if (!(path = virFileBuildPath(priv->configDir, ent->d_name, NULL))) {
                closedir(dh);
                return -1;
            }

            if (xenInotifyAddDomainConfigInfo(conn, path) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("Error adding file to config list"));
                closedir(dh);
                VIR_FREE(path);
                return -1;
            }

            VIR_FREE(path);
        }
        closedir(dh);
    }

    if ((priv->inotifyFD = inotify_init()) < 0) {
        virReportSystemError(errno,
                             "%s", _("initializing inotify"));
        return -1;
    }

    VIR_DEBUG("Adding a watch on %s", priv->configDir);
    if (inotify_add_watch(priv->inotifyFD,
                          priv->configDir,
                          IN_CREATE |
                          IN_CLOSE_WRITE | IN_DELETE |
                          IN_MOVED_TO | IN_MOVED_FROM) < 0) {
        virReportSystemError(errno,
                             _("adding watch on %s"),
                             priv->configDir);
        return -1;
    }

    VIR_DEBUG("Building initial config cache");
    if (priv->useXenConfigCache &&
        xenXMConfigCacheRefresh(conn) < 0) {
        VIR_DEBUG("Failed to enable XM config cache %s", conn->err.message);
        return -1;
    }

    VIR_DEBUG("Registering with event loop");
    /* Add the handle for monitoring */
    if ((priv->inotifyWatch = virEventAddHandle(priv->inotifyFD, VIR_EVENT_HANDLE_READABLE,
                                                xenInotifyEvent, conn, NULL)) < 0) {
        VIR_DEBUG("Failed to add inotify handle, disabling events");
    }

    return 0;
}
示例#6
0
文件: LIRC.cpp 项目: intrcomp/xbmc
bool CRemoteControl::Connect(struct sockaddr_un addr, bool logMessages)
{
  bool bResult = false;
  // Open the socket from which we will receive the remote commands
  if ((m_fd = socket(AF_UNIX, SOCK_STREAM, 0)) != -1)
  {
    // Connect to the socket
    if (connect(m_fd, (struct sockaddr *)&addr, sizeof(addr)) != -1)
    {
      int opts;
      if ((opts = fcntl(m_fd, F_GETFL)) != -1)
      {
        // Set the socket to non-blocking
        opts = (opts | O_NONBLOCK);
        if (fcntl(m_fd, F_SETFL, opts) != -1)
        {
          if ((m_file = fdopen(m_fd, "r+")) != NULL)
          {
#ifdef HAVE_INOTIFY
            // Setup inotify so we can disconnect if lircd is restarted
            if ((m_inotify_fd = inotify_init()) >= 0)
            {
              // Set the fd non-blocking
              if ((opts = fcntl(m_inotify_fd, F_GETFL)) != -1)
              {
                opts |= O_NONBLOCK;
                if (fcntl(m_inotify_fd, F_SETFL, opts) != -1)
                {
                  // Set an inotify watch on the lirc device
                  if ((m_inotify_wd = inotify_add_watch(m_inotify_fd, m_deviceName.c_str(), IN_DELETE_SELF)) != -1)
                  {
                    bResult = true;
                    CLog::Log(LOGINFO, "LIRC %s: successfully started", __FUNCTION__);
                  }
                  else
                    CLog::Log(LOGDEBUG, "LIRC: Failed to initialize Inotify. LIRC device will not be monitored.");
                }
              }
            }
#else
            bResult = true;
            CLog::Log(LOGINFO, "LIRC %s: successfully started", __FUNCTION__);
#endif
          }
          else
            CLog::Log(LOGERROR, "LIRC %s: fdopen failed: %s", __FUNCTION__, strerror(errno));
        }
        else
          CLog::Log(LOGERROR, "LIRC %s: fcntl(F_SETFL) failed: %s", __FUNCTION__, strerror(errno));
      }
      else
        CLog::Log(LOGERROR, "LIRC %s: fcntl(F_GETFL) failed: %s", __FUNCTION__, strerror(errno));
    }
    else if (logMessages)
      CLog::Log(LOGINFO, "LIRC %s: connect failed: %s", __FUNCTION__, strerror(errno));
  }
  else if (logMessages)
    CLog::Log(LOGINFO, "LIRC %s: socket failed: %s", __FUNCTION__, strerror(errno));

  return bResult;
}
示例#7
0
int getevent_main(int argc, char *argv[])
{
    int c;
    int i;
    int res;
    int get_time = 0;
    int print_device = 0;
    char *newline = "\n";
    uint16_t get_switch = 0;
    struct input_event event;
    int print_flags = 0;
    int print_flags_set = 0;
    int dont_block = -1;
    int event_count = 0;
    int sync_rate = 0;
    int64_t last_sync_time = 0;
    const char *device = NULL;
    const char *device_path = "/dev/input";

    opterr = 0;
    do {
        c = getopt(argc, argv, "tns:Sv::dpilqc:rh");
        if (c == EOF)
            break;
        switch (c) {
        case 't':
            get_time = 1;
            break;
        case 'n':
            newline = "";
            break;
        case 's':
            get_switch = strtoul(optarg, NULL, 0);
            if(dont_block == -1)
                dont_block = 1;
            break;
        case 'S':
            get_switch = ~0;
            if(dont_block == -1)
                dont_block = 1;
            break;
        case 'v':
            if(optarg)
                print_flags |= strtoul(optarg, NULL, 0);
            else
                print_flags |= PRINT_DEVICE | PRINT_DEVICE_NAME | PRINT_DEVICE_INFO | PRINT_VERSION;
            print_flags_set = 1;
            break;
        case 'd':
            print_flags |= PRINT_HID_DESCRIPTOR;
            break;
        case 'p':
            print_flags |= PRINT_DEVICE_ERRORS | PRINT_DEVICE
                    | PRINT_DEVICE_NAME | PRINT_POSSIBLE_EVENTS | PRINT_INPUT_PROPS;
            print_flags_set = 1;
            if(dont_block == -1)
                dont_block = 1;
            break;
        case 'i':
            print_flags |= PRINT_ALL_INFO;
            print_flags_set = 1;
            if(dont_block == -1)
                dont_block = 1;
            break;
        case 'l':
            print_flags |= PRINT_LABELS;
            break;
        case 'q':
            print_flags_set = 1;
            break;
        case 'c':
            event_count = atoi(optarg);
            dont_block = 0;
            break;
        case 'r':
            sync_rate = 1;
            break;
        case '?':
            fprintf(stderr, "%s: invalid option -%c\n",
                argv[0], optopt);
        case 'h':
            usage(argv[0]);
            exit(1);
        }
    } while (1);
    if(dont_block == -1)
        dont_block = 0;

    if (optind + 1 == argc) {
        device = argv[optind];
        optind++;
    }
    if (optind != argc) {
        usage(argv[0]);
        exit(1);
    }
    nfds = 1;
    ufds = calloc(1, sizeof(ufds[0]));
    ufds[0].fd = inotify_init();
    ufds[0].events = POLLIN;
    if(device) {
        if(!print_flags_set)
            print_flags |= PRINT_DEVICE_ERRORS;
        res = open_device(device, print_flags);
        if(res < 0) {
            return 1;
        }
    } else {
        if(!print_flags_set)
            print_flags |= PRINT_DEVICE_ERRORS | PRINT_DEVICE | PRINT_DEVICE_NAME;
        print_device = 1;
		res = inotify_add_watch(ufds[0].fd, device_path, IN_DELETE | IN_CREATE);
        if(res < 0) {
            fprintf(stderr, "could not add watch for %s, %s\n", device_path, strerror(errno));
            return 1;
        }
        res = scan_dir(device_path, print_flags);
        if(res < 0) {
            fprintf(stderr, "scan dir failed for %s\n", device_path);
            return 1;
        }
    }

    if(get_switch) {
        for(i = 1; i < nfds; i++) {
            uint16_t sw;
            res = ioctl(ufds[i].fd, EVIOCGSW(1), &sw);
            if(res < 0) {
                fprintf(stderr, "could not get switch state, %s\n", strerror(errno));
                return 1;
            }
            sw &= get_switch;
            printf("%04x%s", sw, newline);
        }
    }

    if(dont_block)
        return 0;

    while(1) {
        //int pollres =
        poll(ufds, nfds, -1);
        //printf("poll %d, returned %d\n", nfds, pollres);
        if(ufds[0].revents & POLLIN) {
            read_notify(device_path, ufds[0].fd, print_flags);
        }
        for(i = 1; i < nfds; i++) {
            if(ufds[i].revents) {
                if(ufds[i].revents & POLLIN) {
                    res = read(ufds[i].fd, &event, sizeof(event));
                    if(res < (int)sizeof(event)) {
                        fprintf(stderr, "could not get event\n");
                        return 1;
                    }
                    if(get_time) {
                        printf("[%8ld.%06ld] ", event.time.tv_sec, event.time.tv_usec);
                    }
                    if(print_device)
                        printf("%s: ", device_names[i]);
                    print_event(event.type, event.code, event.value, print_flags);
                    if(sync_rate && event.type == 0 && event.code == 0) {
                        int64_t now = event.time.tv_sec * 1000000LL + event.time.tv_usec;
                        if(last_sync_time)
                            printf(" rate %lld", 1000000LL / (now - last_sync_time));
                        last_sync_time = now;
                    }
                    printf("%s", newline);
                    if(event_count && --event_count == 0)
                        return 0;
                }
            }
        }
    }

    return 0;
}
示例#8
0
void *watch_temp()

{
    int length, i = 0, wd;
    int fd;
    char buffer[BUF_LEN];

    int wds[MAX_WTD];	//for the wds
    int trigger[MAX_WTD];	//for the event->wd that trigger the current wds
    String dirs[MAX_WTD];	//for the directory names that is trigger by the wds
    int counter = 1;

    /*Initialize inotify*/
    fd = inotify_init();
    if ( fd < 0 ) {
       perror( "Couldn't initialize inotify" );
    }
    /*add watch to directory*/
    wd = inotify_add_watch(fd, TEMP_LOC, IN_ALL_EVENTS);
    wds[counter-1] = wd;
    strcpy(dirs[counter-1], TEMP_LOC);

    if (wd == -1){
        syslog(LOG_INFO, "FileTransaction: Couldn't add watch to %s\n", TEMP_LOC);
    } else {
        syslog(LOG_INFO, "FileTransaction: WRITE :: Watching:: %s\n", TEMP_LOC);

    }

    /*do it forever*/
    while(1){
	//select(fd+1, &descriptors, NULL, NULL, &time_to_wait);
       create_link();
       i = 0;
       length = read(fd, buffer, BUF_LEN);

       if (length < 0){
          perror("read");
       }
       while(i < length){
           struct inotify_event *event = (struct inotify_event *) &buffer[i];

           if (event->len){

	      if (event->mask & IN_CREATE){
		if (event->mask & IN_ISDIR){
		     //printf("%s is created.\n", event->name);
		     String dir_to_watch = "";
		     String root = "";
		     String arr[MAXDEPTH];
		     int d;
		    //Initialize array....
		     for (d = 0; d < 30; d++){
			strcpy(arr[d], "");
		     }

		     get_root(wds,trigger, dirs, counter,event->wd,arr);

		     for (d = 1; d < counter; d++){
			if(strcmp(arr[d], "") != 0) {
			    strcat(root, arr[d]);
			    strcat(root, "/");
			}
		     }

		     String x;
		     sprintf(x, "%s%s", root, event->name);

                     sprintf(dir_to_watch,"%s/%s%s/", TEMP_LOC, root, event->name);
		     wd = inotify_add_watch(fd, dir_to_watch, IN_ALL_EVENTS);

                     if (wd == -1){

		     } else {
			syslog(LOG_INFO, "FileTransaction: WRITE := Watching := %s\n", dir_to_watch);
		     }
		     //printf("DIR_TO_WATCH := %s\n", dir_to_watch);

		     wds[counter] = wd;
		     trigger[counter] = event->wd;
                     strcpy(dirs[counter], event->name);



		/***************CREATES in /mnt/CVFSFSTorage AND LINK DIRECTORY to SHare *********/
		     String dir = "", chmod = "",  sors = "", dest = "";
		     sprintf(dir, "mkdir '%s/%s'", SHIT_STORAGE, event->name);
		     system(dir);

                    sprintf(chmod, "chmod 777 -R '%s/%s'", SHIT_STORAGE, event->name);
		    system(chmod);

		     sprintf(sors, "%s/%s", SHIT_STORAGE, event->name);
		     sprintf(dest, "%s/%s", SHARE_LOC, x);
		     symlink(sors,dest);
	         /******************************************************************************/
		     make_folder(x);
		     counter++;
		}
              }

              if (event->mask & IN_CLOSE){
		if (event->mask & IN_ISDIR){
		} else {
		     String root = "";
		     String arr[MAXDEPTH];
		     int n = sizeof(wds) / sizeof(wds[0]);
		     int d, i, rooti;
		      //initialize the array...
		      for (d = 0; d < MAXDEPTH; d++){
			strcpy(arr[d], "");
		      }


		      get_root(wds, trigger, dirs, counter, event->wd, arr);
		      for (d = 1; d < counter; d++){
			if(strcmp(arr[d], "") != 0) {
			    strcat(root, arr[d]);
			    strcat(root, "/");
			}
		      }

                      String filepath = "";
		      String filename = "";
		      sprintf(filename, "%s%s", root, event->name);
                      FILE *fp;
                      sprintf(filepath, "%s/%s%s", TEMP_LOC, root, event->name);
		      //syslog(LOG_INFO, "FileTransaction: FILEPATH := %s\n", filepath);
		      //syslog(LOG_INFO, "FileTransaction: hahahaa: filepath:%s\n\tfilename:%s", filepath, filename);
                      fp = fopen(filepath, "rb");
                      if (fp != NULL){
                         fseek(fp, 0L, SEEK_END);
                         long sz = ftell(fp);
                         rewind(fp);
                         //check if stripe file
                        if (sz > STRIPE_SIZE){
                           //before striping, check cache
			   printf("STRIPED: %s | SIZE : %ld bytes\n", event->name, sz);
                           //printf("%s will be striped.\n", event->name);
			   //printf("Inserting into CacheContent...\n");
                           update_cache_list(event->name, root);
                           //printf("Cache Count: %d\n", getCacheCount());
                          // if (getCacheCount() < MAX_CACHE_SIZE) { //max cache size is 10
                           printf("Cache Size: %d\n", getCacheCount());
			   printf("%s will be put to cache.\n", filename);
                           file_map_cache(filename, event->name);
                             //create_link_cache(filename);
                          // }
                           //stripe(event->n);
                           //refreshCache();	
			   //printf("ROOT = %s\n", root);
			   //printf("FILEPATH := %s\n", filepath);
			   //printf("FILENAME := %s\n", filename);
			   stripe(root, filepath, filename);
			   //refreshCache();
                        } else {
			   syslog(LOG_INFO, "FileTransaction: Transferring %s to targets...\n", filename);
                           file_map(filepath, filename);
                        }
		    }
                  }
              }

              if (event->mask & IN_MOVED_TO){
                 if (event->mask & IN_ISDIR)
                      printf("The directory %s is transferring.\n", event->name);
                  else
                      printf("The file %s is transferring.\n", event->name);

              }

              i += EVENT_SIZE + event->len;
           }
       }
    }
    /* Clean up */
    inotify_rm_watch(fd, wd);
    close(fd);
}
示例#9
0
文件: crl.c 项目: Nathanrauch/cyassl
/* linux monitoring */
static void* DoMonitor(void* arg)
{
    int         notifyFd;
    int         wd;
    CYASSL_CRL* crl = (CYASSL_CRL*)arg;

    CYASSL_ENTER("DoMonitor");

    crl->mfd = eventfd(0, 0);  /* our custom shutdown event */
    if (crl->mfd < 0) {
        CYASSL_MSG("eventfd failed");
        return NULL;
    }

    notifyFd = inotify_init();
    if (notifyFd < 0) {
        CYASSL_MSG("inotify failed");
        close(crl->mfd);
        return NULL;
    }

    if (crl->monitors[0].path) {
        wd = inotify_add_watch(notifyFd, crl->monitors[0].path, IN_CLOSE_WRITE |
                                                                IN_DELETE);
        if (wd < 0) {
            CYASSL_MSG("PEM notify add watch failed");
            close(crl->mfd);
            close(notifyFd);
            return NULL;
        }
    }

    if (crl->monitors[1].path) {
        wd = inotify_add_watch(notifyFd, crl->monitors[1].path, IN_CLOSE_WRITE |
                                                                IN_DELETE);
        if (wd < 0) {
            CYASSL_MSG("DER notify add watch failed");
            close(crl->mfd);
            close(notifyFd);
            return NULL;
        }
    }

    for (;;) {
        fd_set        readfds;
        char          buff[8192];
        int           result, length;

        FD_ZERO(&readfds);
        FD_SET(notifyFd, &readfds);
        FD_SET(crl->mfd, &readfds);

        result = select(max(notifyFd, crl->mfd) + 1, &readfds, NULL, NULL,NULL);
       
        CYASSL_MSG("Got notify event");

        if (result < 0) {
            CYASSL_MSG("select problem, continue");
            continue;
        }

        if (FD_ISSET(crl->mfd, &readfds)) {
            CYASSL_MSG("got custom shutdown event, breaking out");
            break;
        }

        length = read(notifyFd, buff, sizeof(buff));
        if (length < 0) {
            CYASSL_MSG("notify read problem, continue");
            continue;
        } 

        if (SwapLists(crl) < 0) {
            CYASSL_MSG("SwapLists problem, continue");
        }
    }

    inotify_rm_watch(notifyFd, wd);
    close(crl->mfd);
    close(notifyFd);

    return NULL;
}
示例#10
0
int
main(int argc, char *argv[])
{
    int inotifyFd, childFd, maxFd, wd, j, rst;
    fd_set      fds;
    struct timeval timeout;
    (void)j;
    char buf[BUF_LEN] __attribute__ ((aligned(8)));
    ssize_t numRead;
    char *p;
    struct inotify_event *event;

    if (argc < 3 || strcmp(argv[1], "--help") == 0)
        error_exit("%s pathname childname\n", argv[0]);

    inotifyFd = inotify_init();                 /* Create inotify instance */
    if (inotifyFd == -1)
        error_exit("inotify_init");

    childFd = inotify_init();
    if (childFd == -1)
        error_exit("inotify_init");
    maxFd = inotifyFd > childFd ? inotifyFd : childFd;
    printf("Parent:%d, childFd:%d, maxFd:%d\n", 
            inotifyFd, childFd, maxFd);

    /*for (j = 1; j < argc; j++) {*/
        /*wd = inotify_add_watch(inotifyFd, argv[j], IN_ALL_EVENTS);*/
        /*if (wd == -1)*/
            /*error_exit("inotify_add_watch");*/

        /*printf("Watching %s using wd %d\n", argv[j], wd);*/
    /*}*/
    wd = inotify_add_watch(inotifyFd, argv[1], PARENT_EVENTS);
    if (wd == -1) {                             /* parent inotify */
        error_exit("Parent directory(inotify_add_watch) failed");
    }
    wd = inotify_add_watch(childFd, argv[2], CHILD_EVENTS);
    if (wd == -1) {                             /* children inotify */
        error_exit("Children directory(inotify_add_watch) failed");
    }

    for (;;) {                                  /* Read events forever */
        FD_ZERO(&fds);               
        FD_SET(inotifyFd, &fds);        
        FD_SET(childFd, &fds);        
        timeout.tv_sec = 2; 
        timeout.tv_usec = 0;

        rst = select(maxFd+1, &fds, NULL, NULL, &timeout);
        if (rst <= 0) {
            continue;
        }

        if (FD_ISSET(childFd, &fds)) {
            numRead = read(childFd, buf, BUF_LEN);
            if (numRead == 0)
                error_exit("read() from inotify fd returned 0!");

            if (numRead == -1)
                error_exit("read");
            printf("Read %ld bytes from children inotify fd\n", 
                    (long) numRead);
        } else {
            numRead = read(inotifyFd, buf, BUF_LEN);
            if (numRead == 0)
                error_exit("read() from inotify fd returned 0!");

            if (numRead == -1)
                error_exit("read");
            printf("Read %ld bytes from parent inotify fd\n", 
                    (long) numRead);
        }

        /* Process all of the events in buffer returned by read() */

        for (p = buf; p < buf + numRead; ) {
            event = (struct inotify_event *) p;
            displayInotifyEvent(event);

            p += sizeof(struct inotify_event) + event->len;
        }
    }

    exit(EXIT_SUCCESS);
}
示例#11
0
int main( int argc, char **argv ) 
{
	int length, i = 0, wd;
	int fd;
	char buffer[BUF_LEN];
    
	time_t timer;

	char buffer2[25];
	char *s=NULL;
	struct tm* tm_info;

	FILE *fk;
	//char buffer[EVENT_BUF_LEN];
	char str1[] = "File has been updated at time :";
    
	time_t now;
	struct tm *tm;

	/*now = time(0);
	if ((tm = localtime (&now)) == NULL) {
		printf ("Error extracting time stuff\n");
		return 1;
	} */
	
	fk = fopen( "/home/technoworld/Desktop/file.txt" , "w" );   

	/* Initialize Inotify*/
	fd = inotify_init();
	if ( fd < 0 ) {
		perror( "Couldn't initialize inotify");
	}

	/* add watch to starting directory */
	wd = inotify_add_watch(fd, argv[1], IN_MODIFY );   // Listen to Change in file. Same can done for Delete and create using 	IN_Modify and IN_CREATE
	if (wd == -1){
		printf("Couldn't add listen to %s\n",argv[1]);
	}
	else{
		printf("Listening: %s\n",argv[1]);
	}

	/* do it forever*/
	while(1){
	
		now = time(0);
		if ((tm = localtime (&now)) == NULL) {
			printf ("Error extracting time stuff\n");
			return 1;
		}
		
	      fk = fopen( "file.txt" , "a" );
	      i = 0;
	      length = read( fd, buffer, BUF_LEN );  

		if ( length < 0 ) {
		        perror( "read" );
	        }  

		while ( i < length ) {
			struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
			if ( event->len ) {         
			  if ( event->mask & IN_MODIFY){
				if (event->mask & IN_ISDIR)
			        printf( "The directory %s was modified.\n", event->name );       
		 	        else{
			        	printf( "The file %s was modified see log file for time stamp \n", event->name  ); 
			    		fprintf(fk,"%s %04d-%02d-%02d %02d:%02d:%02d %c",str1, tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,tm->tm_hour, tm->tm_min, tm->tm_sec , '\n');
			    	//Here time can be achieved in various format as per requirement
				}
			  }
			  
			i += EVENT_SIZE + event->len;
			}
     		 }
	fclose(fk);
	}

  /* Clean up*/
  inotify_rm_watch( fd, wd );
  close( fd );
  
  return 0;
}
示例#12
0
int inotifyd_main(int argc, char **argv)
{
	int n;
	unsigned mask;
	struct pollfd pfd;
	char **watches; // names of files being watched
	const char *args[5];

	// sanity check: agent and at least one watch must be given
	if (!argv[1] || !argv[2])
		bb_show_usage();

	argv++;
	// inotify_add_watch will number watched files
	// starting from 1, thus watches[0] is unimportant,
	// and 1st file name is watches[1].
	watches = argv;
	args[0] = *argv;
	args[4] = NULL;
	argc -= 2; // number of files we watch

	// open inotify
	pfd.fd = inotify_init();
	if (pfd.fd < 0)
		bb_perror_msg_and_die("no kernel support");

	// setup watches
	while (*++argv) {
		char *path = *argv;
		char *masks = strchr(path, ':');

		mask = 0x0fff; // assuming we want all non-kernel events
		// if mask is specified ->
		if (masks) {
			*masks = '\0'; // split path and mask
			// convert mask names to mask bitset
			mask = 0;
			while (*++masks) {
				const char *found;
				found = memchr(mask_names, *masks, MASK_BITS);
				if (found)
					mask |= (1 << (found - mask_names));
			}
		}
		// add watch
		n = inotify_add_watch(pfd.fd, path, mask);
		if (n < 0)
			bb_perror_msg_and_die("add watch (%s) failed", path);
		//bb_error_msg("added %d [%s]:%4X", n, path, mask);
	}

	// setup signals
	bb_signals(BB_FATAL_SIGS, record_signo);

	// do watch
	pfd.events = POLLIN;
	while (1) {
		int len;
		void *buf;
		struct inotify_event *ie;
 again:
		if (bb_got_signal)
			break;
		n = poll(&pfd, 1, -1);
		// Signal interrupted us?
		if (n < 0 && errno == EINTR)
			goto again;
		// Under Linux, above if() is not necessary.
		// Non-fatal signals, e.g. SIGCHLD, when set to SIG_DFL,
		// are not interrupting poll().
		// Thus we can just break if n <= 0 (see below),
		// because EINTR will happen only on SIGTERM et al.
		// But this might be not true under other Unixes,
		// and is generally way too subtle to depend on.
		if (n <= 0) // strange error?
			break;

		// read out all pending events
		// (NB: len must be int, not ssize_t or long!)
#define eventbuf bb_common_bufsiz1
		setup_common_bufsiz();
		xioctl(pfd.fd, FIONREAD, &len);
		ie = buf = (len <= COMMON_BUFSIZE) ? eventbuf : xmalloc(len);
		len = full_read(pfd.fd, buf, len);
		// process events. N.B. events may vary in length
		while (len > 0) {
			int i;
			// cache relevant events mask
			unsigned m = ie->mask & ((1 << MASK_BITS) - 1);
			if (m) {
				char events[MASK_BITS + 1];
				char *s = events;
				for (i = 0; i < MASK_BITS; ++i, m >>= 1) {
					if ((m & 1) && (mask_names[i] != '\0'))
						*s++ = mask_names[i];
				}
				*s = '\0';
				if (LONE_CHAR(args[0], '-')) {
					/* "inotifyd - FILE": built-in echo */
					printf(ie->len ? "%s\t%s\t%s\n" : "%s\t%s\n", events,
							watches[ie->wd],
							ie->name);
					fflush(stdout);
				} else {
//					bb_error_msg("exec %s %08X\t%s\t%s\t%s", args[0],
//						ie->mask, events, watches[ie->wd], ie->len ? ie->name : "");
					args[1] = events;
					args[2] = watches[ie->wd];
					args[3] = ie->len ? ie->name : NULL;
					spawn_and_wait((char **)args);
				}
				// we are done if all files got final x event
				if (ie->mask & 0x8000) {
					if (--argc <= 0)
						goto done;
					inotify_rm_watch(pfd.fd, ie->wd);
				}
			}
			// next event
			i = sizeof(struct inotify_event) + ie->len;
			len -= i;
			ie = (void*)((char*)ie + i);
		}
		if (eventbuf != buf)
			free(buf);
	} // while (1)
 done:
	return bb_got_signal;
}
int main(int argc, char** argv) {
  if (argc != 2) {
    strncpy(uploads_url, DEFAULT_UPLOADS_URL, MAX_URL_LENGTH);
  } else {
    strncpy(uploads_url, argv[1], MAX_URL_LENGTH);
  }

  openlog("bismark-data-transmit", LOG_PERROR, LOG_USER);

  if (read_bismark_id()) {
    return 1;
  }

  if (initialize_upload_subdirectories() || initialize_upload_directories()) {
    return 1;
  }

  failure_counters = calloc(num_upload_subdirectories,
                            sizeof(failure_counters[0]));
  if (failure_counters == NULL) {
    syslog(LOG_ERR, "main:calloc: %s", strerror(errno));
    return 1;
  }
  if (write_upload_failures_log()) {
    return 1;
  }

  if (initialize_curl()) {
    return 1;
  }

  /* Initialize inotify */
  int inotify_handle = inotify_init();
  if (inotify_handle < 0) {
    syslog(LOG_ERR, "main:inotify_init: %s", strerror(errno));
    return 1;
  }
  int idx;
  watch_descriptors = calloc(num_upload_subdirectories,
                             sizeof(watch_descriptors[0]));
  if (watch_descriptors == NULL) {
    syslog(LOG_ERR, "main:calloc: %s", strerror(errno));
    return 1;
  }
  for (idx = 0; idx < num_upload_subdirectories; ++idx) {
    watch_descriptors[idx] = inotify_add_watch(inotify_handle,
                                               upload_directories[idx],
                                               IN_MOVED_TO);
    if (watch_descriptors[idx] < 0) {
      syslog(LOG_ERR,
             "main:inotify_add_watch(\"%s\"): %s",
             upload_directories[idx],
             strerror(errno));
      return 1;
    }
    syslog(LOG_INFO, "Watching %s", upload_directories[idx]);
  }

  time_t current_time = time(NULL);
  if (current_time < 0) {
    syslog(LOG_ERR, "main:time: %s", strerror(errno));
    return 1;
  }
  time_t last_retry_time = current_time - RETRY_INTERVAL_SECONDS;

  while (1) {
    current_time = time(NULL);
    if (current_time < 0) {
      syslog(LOG_ERR, "main:time: %s", strerror(errno));
      return 1;
    }

    fd_set select_set;
    FD_ZERO(&select_set);
    FD_SET(inotify_handle, &select_set);
    struct timeval select_timeout;
    select_timeout.tv_sec =
        RETRY_INTERVAL_SECONDS - (current_time - last_retry_time);
    if (select_timeout.tv_sec < 0) {
      select_timeout.tv_sec = 0;
    }
    select_timeout.tv_usec = 0;
    int select_result = select(
        inotify_handle + 1, &select_set, NULL, NULL, &select_timeout);
    if (select_result < 0) {
      syslog(LOG_ERR, "main:select: %s", strerror(errno));
      curl_easy_cleanup(curl_handle);
      return 1;
    } else if (select_result > 0) {
      if (FD_ISSET(inotify_handle, &select_set)) {
        char events_buffer[BUF_LEN];
        int length = read(inotify_handle, events_buffer, BUF_LEN);
        if (length < 0) {
          syslog(LOG_ERR, "main:read: %s", strerror(errno));
          curl_easy_cleanup(curl_handle);
          return 1;
        }
        int offset = 0;
        while (offset < length) {
          struct inotify_event* event \
            = (struct inotify_event*)(events_buffer + offset);
          if (event->len && (event->mask & IN_MOVED_TO)) {
            int idx;
            for (idx = 0; idx < num_upload_subdirectories; ++idx) {
              if (event->wd == watch_descriptors[idx]) {
                char absolute_path[PATH_MAX + 1];
                if (join_paths(
                      upload_directories[idx], event->name, absolute_path)) {
                  break;
                }
                syslog(LOG_INFO, "File move detected: %s", absolute_path);
                if (!curl_send(absolute_path, upload_subdirectories[idx])) {
                  if (unlink(absolute_path)) {
                    syslog(LOG_ERR,
                           "main:unlink(\"%s\"): %s",
                           absolute_path,
                           strerror(errno));
                  }
                }
                break;
              }
            }
          }
          offset += sizeof(*event) + event->len;
        }
      }
    } else if (select_result == 0) {
      current_time = time(NULL);
      if (current_time < 0) {
        syslog(LOG_ERR, "main:time: %s", strerror(errno));
        return 1;
      }
      retry_uploads(current_time);
      last_retry_time = time(NULL);
      if (last_retry_time < 0) {
        syslog(LOG_ERR, "main:time: %s", strerror(errno));
        return 1;
      }
    }
  }
  return 0;
}
示例#14
0
static void *dyn_config_start(void *arg)
{
	struct tcmu_config *cfg = arg;
	int monitor, wd, len;
	char buf[BUF_LEN];

	pthread_cleanup_push(dyn_config_cleanup, arg);

	monitor = inotify_init();
	if (monitor == -1) {
		tcmu_err("Failed to init inotify %m\n");
		return NULL;
	}

	wd = inotify_add_watch(monitor, cfg->path, IN_ALL_EVENTS);
	if (wd == -1) {
		tcmu_err("Failed to add \"%s\" to inotify %m\n", cfg->path);
		return NULL;
	}

	tcmu_info("Inotify is watching \"%s\", wd: %d, mask: IN_ALL_EVENTS\n",
		  cfg->path, wd);

	while (1) {
		struct inotify_event *event;
		char *p;

		len = read(monitor, buf, BUF_LEN);
		if (len == -1) {
			tcmu_warn("Failed to read inotify: %m\n");
			continue;
		}

		for (p = buf; p < buf + len;) {
			event = (struct inotify_event *)p;

			tcmu_info("event->mask: 0x%x\n", event->mask);

			if (event->wd != wd)
				continue;

			/*
			 * If force to write to the unwritable or crashed
			 * config file, the vi/vim will try to move and
			 * delete the config file and then recreate it again
			 * via the *.swp
			 */
			if ((event->mask & IN_IGNORED) && !access(cfg->path, F_OK))
				wd = inotify_add_watch(monitor, cfg->path, IN_ALL_EVENTS);

			/* Try to reload the config file */
			if (event->mask & IN_MODIFY || event->mask & IN_IGNORED)
				tcmu_reload_config(cfg);

			p += sizeof(struct inotify_event) + event->len;
		}
	}

	pthread_cleanup_pop(1);

	return NULL;
}
示例#15
0
文件: crl.c 项目: atigyi/wolfssl
/* linux monitoring */
static void* DoMonitor(void* arg)
{
    int         notifyFd;
    int         wd  = -1;
    WOLFSSL_CRL* crl = (WOLFSSL_CRL*)arg;
#ifdef WOLFSSL_SMALL_STACK
    char*       buff;
#else
    char        buff[8192];
#endif

    WOLFSSL_ENTER("DoMonitor");

    crl->mfd = eventfd(0, 0);  /* our custom shutdown event */
    if (crl->mfd < 0) {
        WOLFSSL_MSG("eventfd failed");
        SignalSetup(crl, MONITOR_SETUP_E);
        return NULL;
    }

    notifyFd = inotify_init();
    if (notifyFd < 0) {
        WOLFSSL_MSG("inotify failed");
        close(crl->mfd);
        SignalSetup(crl, MONITOR_SETUP_E);
        return NULL;
    }

    if (crl->monitors[0].path) {
        wd = inotify_add_watch(notifyFd, crl->monitors[0].path, IN_CLOSE_WRITE |
                                                                IN_DELETE);
        if (wd < 0) {
            WOLFSSL_MSG("PEM notify add watch failed");
            close(crl->mfd);
            close(notifyFd);
            SignalSetup(crl, MONITOR_SETUP_E);
            return NULL;
        }
    }

    if (crl->monitors[1].path) {
        wd = inotify_add_watch(notifyFd, crl->monitors[1].path, IN_CLOSE_WRITE |
                                                                IN_DELETE);
        if (wd < 0) {
            WOLFSSL_MSG("DER notify add watch failed");
            close(crl->mfd);
            close(notifyFd);
            SignalSetup(crl, MONITOR_SETUP_E);
            return NULL;
        }
    }

#ifdef WOLFSSL_SMALL_STACK
    buff = (char*)XMALLOC(8192, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (buff == NULL)
        return NULL;
#endif

    /* signal to calling thread we're setup */
    if (SignalSetup(crl, 1) != 0) {
        #ifdef WOLFSSL_SMALL_STACK
            XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        #endif

        if (wd > 0)
            inotify_rm_watch(notifyFd, wd);
        close(crl->mfd);
        close(notifyFd);
        return NULL;
    }

    for (;;) {
        fd_set readfds;
        int    result;
        int    length;

        FD_ZERO(&readfds);
        FD_SET(notifyFd, &readfds);
        FD_SET(crl->mfd, &readfds);

        result = select(max(notifyFd, crl->mfd) + 1, &readfds, NULL, NULL,NULL);

        WOLFSSL_MSG("Got notify event");

        if (result < 0) {
            WOLFSSL_MSG("select problem, continue");
            continue;
        }

        if (FD_ISSET(crl->mfd, &readfds)) {
            WOLFSSL_MSG("got custom shutdown event, breaking out");
            break;
        }

        length = (int) read(notifyFd, buff, 8192);
        if (length < 0) {
            WOLFSSL_MSG("notify read problem, continue");
            continue;
        }

        if (SwapLists(crl) < 0) {
            WOLFSSL_MSG("SwapLists problem, continue");
        }
    }

#ifdef WOLFSSL_SMALL_STACK
    XFREE(buff, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    if (wd > 0)
        inotify_rm_watch(notifyFd, wd);
    close(crl->mfd);
    close(notifyFd);

    return NULL;
}
示例#16
0
文件: monitor.c 项目: mikeswain/cmdfs
void monitor_remove_directory( monitor_t *m, char *name ) {
	// remove all records with leading path as one found
	const char *root = strdup(name);
	wd_t *src = m->wd_lut;
	wd_t *dst = m->wd_lut;
	int new_count = 0;
	int watches_released = 0;
	while (src < m->wd_lut + m->wd_lut_count) {
		if ( strncmp(src->path,root,strlen(root)) ) {
			if ( dst != src )
				*dst++ = *src; // copy
			else
				dst++;
			new_count++;
		}
		else {
			if (src->wd >0) {
				if  (inotify_rm_watch(m->fd,src->wd)) {
					watches_released++;
				}
				else {
					log_warning("Unable to remove watch for %s",src->path);
				}
			}
			free(src->path); // destroy
		}
		src++;
	}
	free((void *)root);
	m->wd_lut_count = new_count;

	/**
	* For every released watch we can add a new one if the request previously
	* wasn't granted due to the inotify limit. These were marked by having a wd=-1 in the list
	*/
	wd_t find = { .wd = -1 };
	wd_t *wd_found = m->wd_lut;
	while ( watches_released > 0) {
			wd_found = bsearch(&find,wd_found,m->wd_lut_count-(wd_found-m->wd_lut),sizeof(wd_t),wd_t_compare);
			if ( wd_found ) {
				wd_found->wd = inotify_add_watch(m->fd,wd_found->path,IN_CREATE | IN_DELETE | IN_CLOSE_WRITE | IN_MOVED_TO | IN_MOVED_FROM);
				if ( wd_found->wd ) {
					watches_released--;
					log_debug("Added watch for pending %s",wd_found->path);//
				}
			}
			else {
				break; // no more needed
			}
	}

}

void *monitor_run( void *_monitor ) {
	log_debug("monitor run");
	monitor_t *m = (monitor_t *)_monitor;
	if ( (m->fd = inotify_init()) != -1) {
		monitor_add_directory(m,m->rootdir);
		int bufsize = 1024 * sizeof(struct inotify_event);
		char *eventbuf = malloc(bufsize);

		for (;;) {
			int r = read(m->fd,eventbuf,bufsize);
			if ( r == 0 || (r < 0 && errno == EINVAL) ) {
				bufsize *= 2;
				eventbuf = realloc(eventbuf,bufsize);
			}
			else if ( r < 0 ) {
				if ( errno == EINTR )
					continue; // debugger
				log_error("Read failed from inotify: %s\n",strerror(errno));
				m->status = errno;
				break;
			}
			else {
				char *eptr = eventbuf;
				while ( eptr < eventbuf+r) {
					struct inotify_event *event = (struct inotify_event *)eptr;
					wd_t find = { .wd = event->wd };
					wd_t *wd_found = bsearch(&find,m->wd_lut,m->wd_lut_count,sizeof(wd_t),wd_t_compare);
					if ( wd_found && event->name && event->len > 0) {
						char name[strlen(wd_found->path) + event->len+2];
						sprintf(name,"%s/",wd_found->path);
						strncat(name, event->name, event->len);
						if ( event->mask & (IN_MOVED_TO | IN_CREATE | IN_MODIFY | IN_CLOSE_WRITE )) {
							struct stat st;
							if ( !stat(name,&st) ) {
								if ( S_ISREG(st.st_mode)) {
									// Is a new file - stat the corresponding file in the fuse namespace to encache
									// if needed
									char dst[strlen(m->mountdir)+strlen(name)+2];
									sprintf(dst,name[0] == '/'?"%s%s":"%s/%s",m->mountdir,name+strlen(m->rootdir));
									if (stat(dst,&st))
										log_warning("Monitor failed to stat %s\n",dst);
									else
										log_debug("New file %s cached",dst);

								}
								else if ( S_ISDIR(st.st_mode)) {
									// is a new directory - watch it, and any subdirs
									monitor_add_directory(m,name);
									log_debug("New directory %s watched",name);
								}
							}

						}
						else if ( event->mask & (IN_DELETE | IN_MOVED_FROM) ) {
							if ( !(event->mask & IN_ISDIR) ) {
								// clean any cached file
								vfile_t *f = file_create_from_src(name);
								file_decache(f);
								file_destroy(f);
								log_debug("File %s decached",name);
							}
							else {
								// directory
								monitor_remove_directory(m,name);
								log_debug("Directory %s removed",name);
							}
						}
					}
					eptr += sizeof(struct inotify_event) + event->len;
				}
			}
		}
		free(eventbuf);
		close(m->fd);
	}
	else {
示例#17
0
void FileSystemWatcher::init()
{
    mFd = inotify_init();
    assert(mFd != -1);
    EventLoop::eventLoop()->registerSocket(mFd, EventLoop::SocketRead, std::bind(&FileSystemWatcher::notifyReadyRead, this));
}
void Java_com_demo_uninstallmonitor_util_AppUtil_beginMonitor(JNIEnv* env,
		jobject thiz, jstring userSerial, jstring url, jstring packageName,
		jstring apkPah) {
	jstring tag = (*env)->NewStringUTF(env, c_TAG);

	// convert Java string to UTF-8
	const char *webUrl = (*env)->GetStringUTFChars(env, url, NULL);
	const char *pkgName = (*env)->GetStringUTFChars(env, packageName, NULL);
	const char *apkDirectory = (*env)->GetStringUTFChars(env, apkPah, NULL);

	LOGI("url:%s", webUrl);
	LOGI("package data directory:%s", pkgName);
	LOGI("apk path:%s", apkDirectory);

	//fork child process to do the monitoring
	pid_t pid = fork();
	//child_pid=pid;
	LOGI("forked child process pid:%d", pid);
	if (pid < 0) {
		//出错log
		LOGE("fork failed!");

	} else if (pid >= 0) {
		/**************************************start observer data directory***********************************************************/
	while(1){
		//开始监听
		LOGI("start observer data directory");

		//子进程目录监听器 "/data/data/com.demo.uninstallmonitor"
		int fileDescriptor = inotify_init();
		if (fileDescriptor < 0) {

			LOGE("inotify_init failed !");

			exit(1);
		}

		//add watch
		int watchDescriptor = inotify_add_watch(fileDescriptor, pkgName,
				IN_DELETE);

		if (watchDescriptor < 0) {
			LOGE("inotify_add_watch failed !");
			exit(1);
		}


		void *event_buffer = malloc(sizeof(struct inotify_event));

		if (event_buffer == NULL) {

			LOGE("malloc failed  !");
			exit(1);
		}

		//If no events have occurred so far, then read() blocks until an event occurs
		 read(fileDescriptor, event_buffer,
				sizeof(struct inotify_event));


		free(event_buffer);

		//remove watch
		inotify_rm_watch(fileDescriptor, IN_DELETE);

		LOGI("directory moved action");
		//apk file is not deleted immediately,so we sleep for a few seconds
		sleep(5);

		/**************************************start apk file check***********************************************************/
		LOGI("start apk file check");
		//use apk to determine if uninstalled
	int	apk_file_descriptor = inotify_init();

		//On success, inotify_add_watch() returns a nonnegative watch descriptor. On error -1 is returned
		int apkDescriptor = inotify_add_watch(apk_file_descriptor, apkDirectory,
				IN_MODIFY);
		LOGI("apk descriptor:%d", apkDescriptor);

		inotify_rm_watch(apk_file_descriptor, IN_MODIFY);

		//apk file was truly deleted
		if (apkDescriptor == -1) {

			//执行命令am start -a android.intent.action.VIEW -d http://www.baidu.com/
			//4.2以上的系统由于用户权限管理更严格,需要加上 --user 0

			LOGI("before loading url");
			if (userSerial == NULL) {

				// 执行命令am start -a android.intent.action.VIEW -d $(url)
				execlp("am", "am", "start", "-a", "android.intent.action.VIEW",
						"-d", webUrl, (char *) NULL);
			} else {
				// 执行命令am start --user userSerial -a android.intent.action.VIEW -d $(url)
				execlp("am", "am", "start", "--user",
						(*env)->GetStringUTFChars(env, userSerial, &b_IS_COPY),
						"-a", "android.intent.action.VIEW", "-d", webUrl,
						(char *) NULL);
			}

			break;
		}

		else if (apkDescriptor >= 1) { //apk file was not deleted

			LOGI("apk exists,go to directory observer");

		}

	}

	} else {
		//父进程直接退出,使子进程被init进程领养,以避免子进程僵死
	}

	// release the Java string and UTF-8
	(*env)->ReleaseStringUTFChars(env, url, webUrl);
	(*env)->ReleaseStringUTFChars(env, packageName, pkgName);
	(*env)->ReleaseStringUTFChars(env, apkPah, apkDirectory);

	LOGI("finish");

	exit(0);

}
示例#19
0
void
event_process(void)
	{
	Event		*event;
	AtCommand	*at;
	SList	*list,
			*prev_link = NULL,
			*next_link,
			*expired_link,
			tmp_link;
	int		minute_tick, five_minute_tick, ten_minute_tick,
			fifteen_minute_tick, thirty_minute_tick, hour_tick, day_tick;
	struct tm		*tm_now;
	static struct tm tm_prev;
	static time_t	t_prev;

	time(&pikrellcam.t_now);
	pikrellcam.second_tick = (pikrellcam.t_now == t_prev) ? FALSE : TRUE;
	t_prev = pikrellcam.t_now;

	if (pikrellcam.second_tick)
		{
		tm_prev = pikrellcam.tm_local;
		tm_now = localtime(&pikrellcam.t_now);
		minute_tick = (tm_now->tm_min != tm_prev.tm_min)  ? TRUE : FALSE;
		pikrellcam.tm_local = *tm_now;
		}
	else
		minute_tick = FALSE;

	if (pikrellcam.state_modified || minute_tick)
		{
		pikrellcam.state_modified = FALSE;
		state_file_write();
		}

	tmp_link.next = NULL;
	for (list = event_list; list; prev_link = list, list = list->next)
		{
		/* Event loop processing is done with the list unlocked until we
		|  have an expired link that must be removed from the list so that
		|  called event functions cad add events to the list.
		|  If another thread adds an event, only the last list->next
		|  will be modified and this loop will catch it or it won't.
		*/
		event = (Event *) list->data;
		if (   (event->time == 0 && event->count == 0)
			|| event->func == NULL
		   )				/* not activated */
			continue;

		if (event->time > 0 && event->time > pikrellcam.t_now)
			continue;
		else if (event->count > 0 && --event->count > 0)
			continue;

		if (pikrellcam.verbose)
			printf("Event func -> [%s] period=%d\n",
						event->name, (int) event->period);
		if (event->func)
			(*event->func)(event->data);
		if (event->period > 0)
			event->time += event->period;
		else
			{
			pthread_mutex_lock(&event_mutex);
			expired_link = list;
			if (list == event_list)
				{
				event_list = list->next;
				tmp_link.next = list->next;
				list = &tmp_link;
				}
			else
				{
				next_link = list->next;
				list = prev_link;
				list->next = next_link;
				}
			free(expired_link->data);
			free(expired_link);
			pthread_mutex_unlock(&event_mutex);
			}
		}

	if (minute_tick)
		{
		char		*p, buf[IBUF_LEN];
		int			i, n, minute_now, minute_at, minute_offset = 0;
		static int	start = TRUE;
		static int	at_notify_fd, at_notify_wd;
		struct inotify_event *event;

		if (at_notify_fd == 0)
			{
			at_notify_fd = inotify_init();
			if (at_notify_fd > 0)
				{
				fcntl(at_notify_fd, F_SETFL,
						fcntl(at_notify_fd, F_GETFL) | O_NONBLOCK);
				at_notify_wd = inotify_add_watch(at_notify_fd,
						pikrellcam.config_dir, IN_CREATE | IN_MODIFY);
				}
			}
		else if (at_notify_wd > 0)
			{
			n = read(at_notify_fd, buf, IBUF_LEN);
			if (n > 0)
				{
				for (i = 0; i < n; i += sizeof(*event) + event->len)
					{
					event = (struct inotify_event *) &buf[i];
					if (   event->len > 0
					    && !strcmp(event->name,  PIKRELLCAM_AT_COMMANDS_CONFIG)
					   )
						at_commands_config_load(pikrellcam.at_commands_config_file);
					}
				}
			}

		tm_now = &pikrellcam.tm_local;
		minute_now = tm_now->tm_hour * 60 + tm_now->tm_min;

		five_minute_tick = ((tm_now->tm_min % 5) == 0) ? TRUE : FALSE;
		ten_minute_tick = ((tm_now->tm_min % 10) == 0) ? TRUE : FALSE;
		fifteen_minute_tick = ((tm_now->tm_min % 15) == 0) ? TRUE : FALSE;
		thirty_minute_tick = ((tm_now->tm_min % 10) == 0) ? TRUE : FALSE;
		hour_tick = (tm_now->tm_hour  != tm_prev.tm_hour)  ? TRUE : FALSE;
		day_tick =  (tm_now->tm_mday  != tm_prev.tm_mday)  ? TRUE : FALSE;

		if (day_tick || !sun.initialized)
			{
			if (sun.initialized)
				{
				char	tbuf[32];

				log_printf_no_timestamp("\n========================================================\n");
				strftime(tbuf, sizeof(tbuf), "%F", localtime(&pikrellcam.t_now));
				log_printf_no_timestamp("%s ================== New Day ==================\n", tbuf);
				log_printf_no_timestamp("========================================================\n");

				strftime(tbuf, sizeof(tbuf), "%F", localtime(&pikrellcam.t_now));
				}
			sun_times_init();
			sun.initialized = TRUE;
			log_lines();
			state_file_write();
			}

		for (list = at_command_list; list; list = list->next)
			{
			at = (AtCommand *) list->data;

			if ((p = strchr(at->at_time, '+')) != NULL)
				minute_offset = atoi(p + 1);
			else if ((p = strchr(at->at_time, '-')) != NULL)
				minute_offset = -atoi(p + 1);

			if (!strcmp(at->at_time, "start"))
				minute_at = start ? minute_now : 0;
			else if (!strcmp(at->at_time, "minute"))
				minute_at = minute_now;
			else if (!strcmp(at->at_time, "5minute"))
				minute_at = five_minute_tick ? minute_now : 0;
			else if (!strcmp(at->at_time, "10minute"))
				minute_at = ten_minute_tick ? minute_now : 0;
			else if (!strcmp(at->at_time, "15minute"))
				minute_at = fifteen_minute_tick ? minute_now : 0;
			else if (!strcmp(at->at_time, "30minute"))
				minute_at = thirty_minute_tick ? minute_now : 0;
			else if (!strcmp(at->at_time, "hour"))
				minute_at = hour_tick ? minute_now : 0;
			else if (!strncmp(at->at_time, "dawn", 4))
				minute_at = sun.dawn + minute_offset;
			else if (!strncmp(at->at_time, "dusk", 4))
				minute_at = sun.dusk + minute_offset;
			else if (!strncmp(at->at_time, "sunrise", 7))
				minute_at = sun.sunrise + minute_offset;
			else if (!strncmp(at->at_time, "sunset", 6))
				minute_at = sun.sunset + minute_offset;
			else if (!strncmp(at->at_time, "nautical_dawn", 13))
				minute_at = sun.nautical_dawn + minute_offset;
			else if (!strncmp(at->at_time, "nautical_dusk", 13))
				minute_at = sun.nautical_dusk + minute_offset;
			else
				{
				minute_at = (int) strtol(at->at_time, &p, 10) * 60;
				if (*p == ':')
					minute_at += strtol(p + 1, NULL, 10);
				else
					{
					minute_at = 0;	/* error in at_time string */
					log_printf("Error in at_command: [%s] bad at_time: [%s]\n",
							at->command, at->at_time);
					}
				}
			if (minute_now != minute_at)
				continue;

			/* Have a time match so check frequency.
			*/
			if (   !strcmp(at->frequency, "daily")
			    || (   !strcmp(at->frequency, "Sat-Sun")
			        && (tm_now->tm_wday == 0 || tm_now->tm_wday == 6)
			       )
			    || (   !strcmp(at->frequency, "Mon-Fri")
			        && tm_now->tm_wday > 0 && tm_now->tm_wday < 6
			       )
			    || (   (p = strstr(weekdays, at->frequency)) != NULL
			        && (p - weekdays) / 3 == tm_now->tm_wday
			       )
			   )
				{
				if (*(at->command) == '@')
					command_process(at->command + 1);
				else
					exec_no_wait(at->command, NULL);
				}
			}
		start = FALSE;
		if (pikrellcam.config_modified)
			config_save(pikrellcam.config_file);
		}
	}
示例#20
0
int main(int argc, char *argv[])
{
 
 int fd;
 
 if( (fd= inotify_init()) == -1)
 {
 	perror("inotify_init");
	return 1;
 }
 if( inotify_add_watch(fd,"test", IN_ALL_EVENTS) == -1)
 {
   perror("inotify_add_watch");
   return 1;
 }
 
 int numRead;
 char *p;
 char buf[BUF_LEN];
 struct inotify_event *event;

 for(;;)
 {
   numRead = read(fd, buf, BUF_LEN); 
   if(numRead == 0)
   {
     printf("read() from inotify returned 0!");
	 return 1;
   }

   if(numRead == -1)
   {
     perror("read");
	 return 1;
   }

   for(p = buf; p< buf + numRead;)
   {
     event = (struct inotify_event *) p;
	 switch (event->mask) {
	  case IN_ACCESS:
	   printf("access\n");
	   break;
	  case IN_ATTRIB:
	   printf("attrib\n");
	   break;
	  case IN_CLOSE_WRITE:
	   printf("close write\n");
	   break;
	  case IN_CLOSE_NOWRITE:
	   printf("close nowrite\n");
	   break;
	  case IN_CREATE:
	   printf("create\n");
	   break;
	  case IN_DELETE:
	     printf("delete\n");
	   break;
	  default:
	    printf("event mask is %d\n",event->mask);
	   
	 }
	 p += sizeof(struct inotify_event) + event->len;
   }
 }


 return 0;
}
示例#21
0
int main(int argc, char **argv) {
	int ret, i;

	FILE *cfg = cfg_open();
	char *statedir = cfg_get_default(cfg, "statedir", STATEDIR);
	cfg_close(cfg);

	for (i = 0; gpios[i].dev; i++) {
		int err = gpio_init(&gpios[i]);
		if (err) {
			fprintf(stderr, "could not init gpio \"%s\": %d!\n", gpios[i].name, err);
			return 1;
		}
	}

	char buffer[EVENT_BUF_LEN];

	state.fd = inotify_init();
	if(state.fd < 0) {
		fprintf(stderr, "Could not init inotify!\n");
		return 1;
	}

	ret = mkdir(statedir, 0775);
	if (ret < 0 && errno != EEXIST) {
		fprintf(stderr, "Could not create statedir: %d\n", ret);
		return 1;
	}

	ret = chmod(statedir, 0775);
	if (ret < 0) {
		fprintf(stderr, "Cannot fix rights on statedir: %d\n", ret);
		return 1;
	}

	state.wd = inotify_add_watch(state.fd, statedir, IN_MODIFY | IN_DELETE);

	state.doorstate = DOOR_UNKNOWN;

	for(;;) {
		int len = read(state.fd, buffer, EVENT_BUF_LEN);
		sleep(1);
		len = read(state.fd, buffer, EVENT_BUF_LEN);

		if(!state_read(statedir, &state.keyholder_id, &state.keyholder_name, &state.status, &state.message)) {
			fprintf(stderr, "Could not read state!\n");
			return 1;
		}

		printf("new state: id=%d name=%s status=%d message=%s\n", state.keyholder_id, state.keyholder_name, state.status, state.message);

		switch(state.status) {
			case STATE_NONE:
				lock();
				state.doorstate = DOOR_LOCKED;
				break;
			case STATE_KEYHOLDER:
			case STATE_MEMBER:
			case STATE_OPEN:
			case STATE_OPEN_PLUS:
				unlock();
				state.doorstate = DOOR_UNLOCKED;
				break;
			case STATE_UNKNOWN:
			default:
				state.doorstate = DOOR_UNKNOWN;
				break;
		}

		free(state.keyholder_name);
		free(state.message);
	}

	inotify_rm_watch(state.fd, state.wd);
	close(state.fd);
}
void daemonize(void) {
  int v_ret;
  pid_t v_pid;
  char v_name[128];
  char v_buf[512];
  struct inotify_event iev;
  struct sigaction    actions;

  v_pid = fork();

  if(v_pid > 0) {
    exit(0);
  }

  sprintf(v_buf,"emw820w_tool (%s) daemonizing ...\n", g_vers);
  logging(ANDROID_LOG_ERROR, v_buf);
  g_loop=1;
  
  close(STDIN_FILENO);
  close(STDOUT_FILENO);
  close(STDERR_FILENO);


  memset(&actions, 0, sizeof(actions));
  sigemptyset(&actions.sa_mask);
  actions.sa_flags = 0;
  actions.sa_handler = sighdl;
  sigaction(SIGTERM,& actions, NULL);

  g_ifd = inotify_init();
  if(g_ifd < 0) {
    sprintf(v_buf,"inotify_init() error %d\n", errno);
    logging(ANDROID_LOG_ERROR, v_buf);
    exit(1);
  }

  logging(ANDROID_LOG_DEBUG, "entering watchdog mode ...\n");

  if(get_mode() != 1404) {
    set_1404();
    sleep(2);
  }
  read_val("/sys/bus/usb/devices/1-1/power/autosuspend", g_curval);

  while(g_loop == 1) {
    getport(v_name);
    
    g_wfd = inotify_add_watch(g_ifd, v_name, IN_DELETE_SELF);
    if(g_wfd < 0) {
      sprintf(v_buf,"watchdog: inotify_add_watch() error %d\n", errno);
      logging(ANDROID_LOG_ERROR, v_buf);
      sleep(2);
    } else {
      sprintf(v_buf,"watchdog for %s initialized\n", v_name);
      logging(ANDROID_LOG_DEBUG, v_buf);
  
      iev.mask = 0;
      while(iev.mask != IN_DELETE_SELF) {
        v_ret=read(g_ifd, &iev, sizeof(iev));
        if(g_loop == 0) {
          break;
        }
      } 
      v_ret = inotify_rm_watch(g_ifd, g_wfd);
      if(g_loop == 1) {
        sleep(5);
        if((v_ret = get_mode()) != 1404) {
          logging(ANDROID_LOG_DEBUG,"3G crash detected!\n");
          logging(ANDROID_LOG_DEBUG,"activating wakelock\n");
          v_ret = write_val("/sys/power/wake_lock", "em820w_tool\n");
          while (v_ret != 1404) {
            set_1404();
            sleep(10);
            v_ret = get_mode();
          }
          logging(ANDROID_LOG_DEBUG,"deactivating wakelock\n");
          v_ret = write_val("/sys/power/wake_unlock", "em820w_tool\n");
        }
        sleep(2);
      }
    }
  }

  logging(ANDROID_LOG_DEBUG,"exiting...\n");
  close(g_wfd);
  close(g_ifd);
  exit(0);
}
示例#23
0
void CRemoteControl::Initialize()
{
  struct sockaddr_un addr;
  unsigned int now = XbmcThreads::SystemClockMillis();

  if (m_bInitialized || !m_used || (now - m_lastInitAttempt) < (unsigned int)m_initRetryPeriod)
    return;
  
  m_lastInitAttempt = now;
  addr.sun_family = AF_UNIX;
  strcpy(addr.sun_path, m_deviceName.c_str());

  CLog::Log(LOGINFO, "LIRC %s: using: %s", __FUNCTION__, addr.sun_path);

  // Open the socket from which we will receive the remote commands
  if ((m_fd = socket(AF_UNIX, SOCK_STREAM, 0)) != -1)
  {
    // Connect to the socket
    if (connect(m_fd, (struct sockaddr *)&addr, sizeof(addr)) != -1)
    {
      int opts;
      m_bLogConnectFailure = true;
      if ((opts = fcntl(m_fd,F_GETFL)) != -1)
      {
        // Set the socket to non-blocking
        opts = (opts | O_NONBLOCK);
        if (fcntl(m_fd,F_SETFL,opts) != -1)
        {
          if ((m_file = fdopen(m_fd, "r+")) != NULL)
          {
#ifdef HAVE_INOTIFY
            // Setup inotify so we can disconnect if lircd is restarted
            if ((m_inotify_fd = inotify_init()) >= 0)
            {
              // Set the fd non-blocking
              if ((opts = fcntl(m_inotify_fd, F_GETFL)) != -1)
              {
                opts |= O_NONBLOCK;
                if (fcntl(m_inotify_fd, F_SETFL, opts) != -1)
                {
                  // Set an inotify watch on the lirc device
                  if ((m_inotify_wd = inotify_add_watch(m_inotify_fd, m_deviceName.c_str(), IN_DELETE_SELF)) != -1)
                  {
                    m_bInitialized = true;
                    CLog::Log(LOGINFO, "LIRC %s: successfully started", __FUNCTION__);
                  }
                  else
                    CLog::Log(LOGDEBUG, "LIRC: Failed to initialize Inotify. LIRC device will not be monitored.");
                }
              }
            }
#else
            m_bInitialized = true;
            CLog::Log(LOGINFO, "LIRC %s: successfully started", __FUNCTION__);
#endif
          }
          else
            CLog::Log(LOGERROR, "LIRC %s: fdopen failed: %s", __FUNCTION__, strerror(errno));
        }
        else
          CLog::Log(LOGERROR, "LIRC %s: fcntl(F_SETFL) failed: %s", __FUNCTION__, strerror(errno));
      }
      else
        CLog::Log(LOGERROR, "LIRC %s: fcntl(F_GETFL) failed: %s", __FUNCTION__, strerror(errno));
    }
    else
    {
      if (m_bLogConnectFailure)
      {
        CLog::Log(LOGINFO, "LIRC %s: connect failed: %s", __FUNCTION__, strerror(errno));
        m_bLogConnectFailure = false;
      }
    }
  }
  else
    CLog::Log(LOGINFO, "LIRC %s: socket failed: %s", __FUNCTION__, strerror(errno));
  if (!m_bInitialized)
  {
    Disconnect();
    m_initRetryPeriod *= 2;
    if (m_initRetryPeriod > 60000)
    {
      m_used = false;
      CLog::Log(LOGDEBUG, "Failed to connect to LIRC. Giving up.");
    }
    else
      CLog::Log(LOGDEBUG, "Failed to connect to LIRC. Retry in %ds.", m_initRetryPeriod/1000);
  }
  else
    m_initRetryPeriod = 5000;
}
示例#24
0
/*----------------------------------------------------------------------*/
int main(int argc,char *argv[])
{
  int                     fd,wd,x;
  ssize_t                 len,i;
  struct inotify_event    equeue[QUEUE_LEN];
  struct watch_list_t*    pwatch_list = watch_list;
  char                    szCommand[BUF_LEN];
  char                    szMessage[BUF_LEN];
  char*                   szFile=NULL;
  char                    szBuffer[BUF_LEN];
  int                     num_watch_files=0;
  int                     nDiff=0;
  char                    szMD5new[BUF_LEN];
  int                     sleep_time=60;
  
  if(argc>1)
  {
    szFile=argv[1];
  } else
  {
    printf("Use:  %s [ini filename]\n",argv[0]);
    exit(-1);
  }
  
#ifdef DAEMONIZE  
  daemon();
#endif
  
  /* get the number of files to watch */
  x=ReadIniArg(szFile, FILEWATCH,"num_files",szBuffer,BUF_LEN);
  if(x)
  {
    num_watch_files=atoi(szBuffer);
  }
  
  /* get the sleep time  */
  x=ReadIniArg(szFile, FILEWATCH,"sleep_time",szBuffer,BUF_LEN);
  if(x)
  {
    sleep_time=atoi(szBuffer);
  }

  sprintf(szMessage,"watching %d files every %d seconds",
          num_watch_files,sleep_time);
  locallog(szMessage);
  

  
  /* set up the basic paramters */
  ReadFileData(szFile,num_watch_files);
  memset(equeue,0,sizeof(struct inotify_event)*QUEUE_LEN);
  fd=inotify_init();
  if(fd==-1)
  {
    perror("inotify_init");
    exit(EXIT_FAILURE);
  }

  /* do the work */
  for(x=0;x<num_watch_files;x++)
  {
    watch_list[x].wd=inotify_add_watch(fd,
                                       watch_list[x].szFile,
                                       IN_CLOSE_WRITE);

    sprintf(szMessage,"watching %s",watch_list[x].szFile);
    locallog(szMessage);
  }

#ifdef EVENT_QUEUE_METHOD  
  while(1)
  {
    len = read (fd,equeue,QUEUE_LEN);
    i=0;
    while(i<len)
    {
      struct inotify_event *event = (struct inotify_event*) &equeue[i];
      if(event->mask && IN_CLOSE_WRITE)
      {
        print_event(event);
        for(x=0;x<MAX_WATCH_FILES;x++)
        {
          if(event->wd == watch_list[x].wd)
          {
            sprintf(szMessage,"file %s closed",watch_list[x].szFile);
            locallog(szMessage);

            /* check the MD5 to see if the file changed */
            MD5File(watch_list[x].szFile,szMD5new);
            nDiff=strcmp(watch_list[x].szMD5,szMD5new);
            if(nDiff)
            {
              DoFileCommand(x);
              strcpy(watch_list[x].szMD5,szMD5new);
            }
          }
        }
      }
      i++;
    }
    sleep(2);
  }
  inotify_rm_watch(fd);
#endif

#ifdef POLLING_METHOD
  while(1)
  {
    sleep(sleep_time);
    for(x=0;x<num_watch_files;x++)
    {
      /* check the MD5 to see if the file changed */
      MD5File(watch_list[x].szFile,szMD5new);
      nDiff=strcmp(watch_list[x].szMD5,szMD5new);
      if(nDiff)
      {
        DoFileCommand(x);
        strcpy(watch_list[x].szMD5,szMD5new);
        sprintf(szMessage,"file %s new MD5: %s",
                watch_list[x].szFile,
                watch_list[x].szMD5);
        locallog(szMessage);
      }
    }
  }
#endif
  
}
示例#25
0
static void sequence_wait(int ipcfd)
{
  struct pollfd fds[4];
  int nfds = 0;
#ifdef PBINOTIFY
  int ifd, wfd;
  ifd = inotify_init();
  if (ifd == -1) {
    perror("inotify_init");
    return;
  }

  wfd = inotify_add_watch(ifd, s(playbackState.synchronization_path), IN_MODIFY);
  printf("ifd=%d\n", ifd);
  printf("wfd=%d\n", wfd);
#endif
  
  fds[0].fd = ipcfd;
  fds[0].events = POLLIN|POLLERR;
  nfds++;

#ifdef PBINOTIFY
  fds[1].fd = ifd;
  fds[1].events = POLLIN|POLLERR;
  nfds++;
#endif

#ifdef PBPIPE
  fds[1].fd = playbackState.wakepipe[0];
  fds[1].events = POLLIN|POLLERR;
  nfds++;
#endif

#ifdef PBEVENTFD
  fds[1].fd = playbackState.wakefd;
  fds[1].events = POLLIN|POLLERR;
  nfds++;
#endif

  int rc = poll(fds, nfds, -1);
  printf("poll rc=%d\n", rc);

  if (fds[0].revents & POLLIN) {
    printf("ipc closed\n");
  }

#ifdef PBEVENTFD
  if (fds[1].revents & POLLIN) {
    uint64_t wake;
    if (read(playbackState.wakefd, &wake, sizeof(wake)) != sizeof(wake)) {
      perror("eventfd read");
    }
    printf("read 1 byte\n");
  }
#endif

#ifdef PBPIPE
  if (fds[1].revents & POLLIN) {
    unsigned char x;
    read(playbackState.wakepipe[0], &x, 1);
    printf("read 1 byte\n");
  }
#endif

#ifdef PBINOTIFY
  inotify_rm_watch(ifd, wfd);
  close(ifd);
#endif
}
示例#26
0
int main() {
  int fd, length, i = 0, status;
  char *file;
  char buf[1000], buf2[1000];
  char buffer[BUF_LEN];
  FILE *fp;

  fd = inotify_init();

  files = malloc(100 * sizeof(char *));
  fp = fopen("watcher.files", "r");
  if(fp == NULL) {
    printf("%sThe list of watchable files is absent.%s", RED, DEFAULT);
    exit(1);
  }
  while(fscanf(fp, "%s", buf) != EOF) {
    files[i] = malloc(1000 * sizeof(char));
    strcpy(files[i], buf);
    i++;
  }
  watched_file_count = i;
  fclose(fp);

  watchers = malloc(watched_file_count * sizeof(int));

  for(i=0; i<watched_file_count; i++) {
    file = files[i];
    watchers[i] = inotify_add_watch(fd, file, IN_CLOSE_WRITE);
    if(watchers[i] > 0 && watchers[i] < 100) {
      printf("%sWatching %s.%s\n", GREEN, file, DEFAULT);
    }
    else {
      printf("%sError watching %s.%s\n", RED, file, DEFAULT);
    }
  }

  while(1) {
    i = 0;
    length = read(fd, buffer, BUF_LEN);

    if(length < 0) {
      printf("%sError in reading inotify event.%s\n", RED, DEFAULT);
    }

    while(i < length) {
      struct inotify_event *event = (struct inotify_event *) &buffer[i];
      char *filename = watcher_to_file(event->wd);
      printf("\n%sFile %s modified.%s\n", BOLD_BLUE, filename, DEFAULT);

      fp = fopen("watcher.commands", "r");
      if(fp == NULL) {
	printf("%sThe list of post-file-modification commands is absent.%s\n", RED, DEFAULT);
	exit(1);
      }
      while(fgets(buf, sizeof(buf), fp) != NULL) {    // fgets() returns NULL on EOF or error
	sprintf(buf2, buf, filename);
	trim(buf, sizeof(buf), buf2);	
	if(strcmp(buf, "") != 0) {
	  printf("%sRunning '%s'...%s\n", CYAN, buf, DEFAULT);
	  status = system(buf);
	  if(status == 0)
	    printf("%sdone.%s\n", GREEN, DEFAULT);
	  else {
	    printf("%sfailed.%s\n", RED, DEFAULT);
	  }
	}
      }
      fclose(fp);

      i += EVENT_SIZE + event->len;
    }
  }

  close(fd);

  return 0;
}
示例#27
0
int main(int argc, char *argv[]) {
  char *pendulumdatapath = "data_pendulum";
  char *dumppath = NULL;
  
  for (int i = 1; i < argc; i++) {
    if (argcmpass("--pendulum|-p", argc, argv, &i, &pendulumdatapath)) ;
    else if (argcmpass("--datafilepath|-d", argc, argv, &i, &datafilepath)) ;
    else if (argcmpass("--dump|-D", argc, argv, &i, &dumppath)) ;
    else if (ARGCMP("--whitebg", i)) {
      whitebg = 1;
    }
    else if (ARGCMP("--no-show-normal-lines", i)) show_normal_lines = false;
    else if (argcmpassdouble("--l1", argc, argv, &i, &l1)) ;
    else if (argcmpassdouble("--l2b", argc, argv, &i, &l2b)) ;
    else fprintf(stderr, "warning: Unknown argument ignored: \"%s\"\n", argv[i]);
  }
  
  if (l1 <= 0 || l2b <= 0) {
    fprintf(stderr, "l1 and l2b must be >0\n");
    exit(1);
  }
  
  // x11 things
  sf = createSHMSurface(100, 100, 500, 500);
  
  int in_fd = -1;
  if (dumppath == NULL) {
    in_fd = inotify_init();
    if (in_fd == -1) {
      fprintf(stderr, "can't create inotify fd: %s\n", strerror(errno));
      exit(1);
    }
    int in_watch = inotify_add_watch(in_fd, datafilepath, IN_CLOSE_WRITE);
    if (in_watch == -1) {
      fprintf(stderr, "can't create inotify watch: %s\n", strerror(errno));
      exit(1);
    }
  }
  
  run();
  
  if (dumppath != NULL) {
    int fd = open(dumppath, O_WRONLY|O_CREAT|O_TRUNC, 0777);
    if (fd == -1) {
      fprintf(stderr, "can't open \"%s\" for writing: %s\n", dumppath, strerror(errno));
      exit(1);
    }
    dump_ppm(fd, sf);
    close(fd);
    return 0;
  }
  
  while (1) {
    size_t evt_size = sizeof(struct inotify_event)+NAME_MAX+1;
    struct inotify_event *evt = alloca(evt_size);
    int readres = read(in_fd, evt, evt_size);
    if (readres == 0) {
      fprintf(stderr, "inotify EOF\n");
      exit(1);
    }
    if (readres == -1) {
      fprintf(stderr, "inotify read error: %s\n", strerror(errno));
      exit(1);
    }
    // we ignore the actual inotify event – there's only one thing it could
    // plausibly be, and if we're wrong, we just run one more iteration
    run();
  }
}
示例#28
0
UnixFileWatcher::UnixFileWatcher()
:   _isRunning(false)
{
    if ((_inotifyFd = inotify_init()) == -1)
        throw (std::runtime_error(getErrorString("inotify_init", errno)));
}
//------------------------------------------------------------------------------------------------
int HA_ccifs::ccifs_inotify()
{
                ACE_Trace _( ACE_TEXT( "HA_ccifs::ccifs_inotify" ) , __LINE__ );


                static size_t BUF_LEN { 10 * (sizeof(struct inotify_event) + NAME_MAX + 1 ) };
                int inotify_fd, wd;
                char buf[BUF_LEN] __attribute__ ((aligned(8)));
                ssize_t num_read;
                char *p;
                struct inotify_event *event;


                //instantiate inotify interface
                inotify_fd = inotify_init();
                if( inotify_fd == -1 )
                {
                    ACE_ERROR_RETURN ((LM_ERROR,
                                       ACE_TEXT ( "HA_ccifs notify init")
                                       ACE_TEXT (" failed\n") ) ,
                                      -1 );
                }

                ACE_DEBUG
                  ((LM_NOTICE, ACE_TEXT ("%D (%t) ccifs:..initialized inotify interace..\n") ) );

                wd = inotify_add_watch( inotify_fd ,
                                        m_str_tmpfs.c_str() ,
                                        IN_ALL_EVENTS );
                if( wd == -1 )
                {
                      ACE_ERROR_RETURN ((LM_ERROR,
                                       ACE_TEXT ( "ccifs: add notifiy watch...")
                                       ACE_TEXT (" failed\n") ) ,
                                      -1 );

                }

                ACE_DEBUG((LM_NOTICE , "%D(%t) ccifs added notify watch=>%s\n",
                                            m_str_tmpfs.c_str() ) );


                while( running() )
                {

                      num_read = read( inotify_fd ,
                                       buf ,
                                       BUF_LEN );
                      if( num_read == 0 )
                      {
                             ACE_ERROR_RETURN ((LM_ERROR,
                                       ACE_TEXT ( "ccifs: read() from inotify fd returned 0...")
                                       ACE_TEXT (" failed\n") ) ,
                                      -1 );
                     }
                     if( num_read == -1 )
                     {

                            ACE_ERROR_RETURN ((LM_ERROR,
                                       ACE_TEXT ( "ccifs: read ")
                                       ACE_TEXT (" failed...\n") ) ,
                                      -1 );
                     }

                     //process elements in buffer
                     for ( p = buf; p < buf + num_read; )
                     {
                        event = (struct inotify_event*) p;
                        display_inotify_event( event );

                        p += sizeof(struct inotify_event) + event->len;
                     }

                     //std::this_thread::sleep_for( std::chrono::milliseconds( 250 ) );
                }




                return 0;
}
示例#30
0
void FileWatcher::run() {
	const auto fd = inotify_init();
	if(fd == -1) {
		throw std::runtime_error {"inotify_init returned -1"};
	}
	
	std::unordered_map<int, Map::iterator> wdIt;
	
	const auto flags = IN_MODIFY;
	
	for(Map::iterator it = pathOnChange.begin(); it != pathOnChange.end(); it++) {
		const std::string& path = it->first;
		
		const auto wd = inotify_add_watch(fd, path.c_str(), flags);
		if(wd == -1) {
			if(!Utils::isFileAccessible(path)) {
				std::cerr << "Error: can't monitor file '" << path << "'" << std::endl;
				continue;
			}
			throw std::runtime_error {"inotify_add_watch returned -1"};
		}
		else {
			wdIt.emplace(wd, it);
		}
	}
	
	while(true) {
		const size_t bufferLength = (sizeof(inotify_event) + PATH_MAX + 1) * 10;
		char buffer[bufferLength];
	
		const auto numRead = read(fd, buffer, bufferLength);
		if(numRead == 0) {
			throw std::runtime_error {"read() from inotify fd returned 0"};
		}
		else if(numRead == -1) {
			throw std::runtime_error {"read() from inotify fd returned -1"};
		}
	
		for(char* p = buffer; p < buffer + numRead; ) {
			const auto event = reinterpret_cast<inotify_event*>(p);
			const auto wd = event->wd;
			const auto it = wdIt.at(wd);
			const std::string& path = it->first;
			
			if(event->mask & IN_IGNORED) {
				inotify_rm_watch(fd, wd);
				const auto newWd = inotify_add_watch(fd, path.c_str(), flags);
				if(newWd == -1) {
					throw std::runtime_error {"inotify_add_watch returned -1"};
				}
				auto itOfWdIt = wdIt.find(wd);
				std::swap(wdIt.at(newWd), itOfWdIt->second);
				wdIt.erase(wd);
			}
			pathOnChange.at(path)();
	
			p += sizeof(inotify_event) + event->len;
		}
	}

	for(const auto pair : wdIt) {
		const auto wd = pair.first;
		inotify_rm_watch(fd, wd);
	}
	close(fd);
}