【问题标题】:Using Linux C select system call to monitor files使用 Linux C select 系统调用来监控文件
【发布时间】:2014-09-10 23:41:51
【问题描述】:

我在以下代码的执行文件夹中创建了两个文件,一个名为test,另一个是test2。我在一个终端中运行以下代码,该终端“监视”这两个文件的更改,但即使没有触摸文件,select 调用也会一直返回。

#include <fcntl.h>      /* fcntl */
#include <sys/select.h> /* select */
#include <stdio.h> /* NULL */

int main() {

    fd_set readfds, writefds;
    int max_fd;

    int fd_1 = open("test", O_RDWR  | O_NONBLOCK);
    int fd_2 = open("test2", O_RDWR | O_NONBLOCK);

    if(fd_1 == -1)
        return -1;

    if(fd_2 == -1)
        return -1;


    while(1) {

        FD_ZERO(&readfds);
        FD_ZERO(&writefds);

        FD_SET(fd_1, &readfds);
        FD_SET(fd_2, &readfds);
        FD_SET(fd_1, &writefds);
        FD_SET(fd_2, &writefds);

        max_fd = (fd_2 > fd_1 ? fd_2 : fd_1) + 1;

        int t_rdy = select(max_fd, &readfds, &writefds, NULL, NULL);

        if(t_rdy == -1)
            return -1;

        int t_fd;
        for(t_fd = 0; t_fd < max_fd; t_fd++) {

            if(t_fd <= 2) continue;

            printf("READ  LIST %d: %s \n", t_fd, (FD_ISSET(t_fd, &readfds) ? "set" : "nope"));
            printf("WRITE LIST %d: %s \n", t_fd, (FD_ISSET(t_fd, &writefds) ? "set" : "nope"));
        }

    }

    return 0;
}

【问题讨论】:

  • 你不应该在这个周期里做sleep吗?另外,如果您没有得到有意义的值,也许只是 continue 而不是 return
  • 如果选择的返回是-1,那是一个错误为什么要继续。无论如何,在这种情况下可能不相关。

标签: c linux file system-calls


【解决方案1】:

这正是我所期望的行为。就select() 而言,磁盘文件总是准备好被读取或写入。

【讨论】:

  • 那我不能用select来监控文件夹中的文件变化吗?
  • @ArmenB。你可以,只是不是那样。
  • (查找 inotify)
猜你喜欢
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多