网上的busybox的源代码看不懂,因为引用了很多别的文件的代码。如果我自己想实现一个类似tail的功能,大概需要什么样的系统调用?关键问题是: 如何实时监控某个文件,当文件产生变化的时候打印出末尾新添加的部分? 给个思路吧

解决方案 »

  1.   

    我也在看busybox中的tail源码,不过它仅仅是文件读取和行分割并显示,并没有实时监控文件变化的功能。它实际上是通过sleep后再打开文件来发现文件变化的: if (FOLLOW) while (1) {
    sleep(sleep_period);  // 等待一段时间 i = 0;
    do {
    int nread;
    const char *filename = argv[i];
    int fd = fds[i]; if (FOLLOW_RETRY) {
    struct stat sbuf, fsbuf; if (fd < 0
     || fstat(fd, &fsbuf) < 0
     || stat(filename, &sbuf) < 0 // 获取当前文件状态
     || fsbuf.st_dev != sbuf.st_dev // 对比文件状态
     || fsbuf.st_ino != sbuf.st_ino //
    ) {
    int new_fd; if (fd >= 0)
    close(fd);
    new_fd = open(filename, O_RDONLY); // 重新打开文件
    if (new_fd >= 0) {
    bb_error_msg("%s has %s; following end of new file",
    filename, (fd < 0) ? "appeared" : "been replaced"
    );
    } else if (fd >= 0) {
    bb_perror_msg("%s has become inaccessible", filename);
    }
    fds[i] = fd = new_fd;
    }
    }
    ...