自定义实现C语言中的“tail -f”功能

2024-10-02 12:32:16 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:我最后使用了inotify。正如stefanB所说,inotify是一个可以使用的东西。我发现了一个尾部克隆,它使用inotify实现-f模式inotail。在

原始问题文本:

我试图在一个C项目中实现“tail-f”逻辑,为了原型化,我用python开发了它,如下所示:


    # A forever loop, each 5 seconds writes a line into file.txt
    from time import *

    while 1:
        sleep(5)
        file = open("file.txt", "a")
        file.write("This is a test\n")
        file.close()

下一个代码遵循文件.txt(以上代码更新)

^{pr2}$

所有的工作都很好,但是C实现不工作(没有检查错误代码)。省略了stdio.h、string.h和unistd.h的包含(彩色化隐藏了头包含代码)。在


    #define LINE_LEN 256

    int main(int argc, char **argv)
    {
        FILE *f;
        char line[LINE_LEN];

        f = fopen("file.txt", "r");

        fseek(f, 0, SEEK_END);

        while (1)
        {
            fgets(line, LINE_LEN, f);

            if (strlen(line) == 0)
            {
                sleep(1);
            }
            else
            {
                printf("Readed: %s", line);
            } 
        }

        fclose(f);

        return 0;
    }

有什么想法吗?在

用poll()而不是呈现的解决方案来实现它是个好主意吗?。在

提前谢谢。在


Tags: 代码txt编辑lenline模式sleepfile
3条回答

编辑: 似乎inotify是要使用的东西。从2.6.13开始,它应该包含在linux内核中。An article from IBM developerworks about inotify。在

上一个答案:

看看Linux File Alteration Monitor(在Linux内核2.4.x>;)中。它是一个框架,允许您订阅文件更改,并在更改发生时从内核获得回调。这应该比投票更好。在

Examples如何轮询文件更改,请查看等待文件更改的部分轮询文件更改。在

我还没试过。在

一旦文件*发现错误或eof,它就设置了其内部状态,以便在后续调用中继续返回error或eof。在睡眠返回后,您需要调用clearerr(f);,以清除eof设置并让它尝试从文件中读取更多数据。在

来自tailman page

-f Do not stop when end-of-file is reached, but rather to wait for additional data to be appended to the input. If the file is replaced (i.e., the inode number changes), tail will reopen the file and continue. If the file is truncated, tail will reset its position to the beginning. This makes tail more useful for watching log files that may get rotated. The -f option is ignored if the standard input is a pipe, but not if it is a FIFO.

所以,你可以做同样的事情:

  1. 使用stat()读取文件的索引节点号
  2. 显示该文件的内容。存储文件描述符的位置,例如p=ftell(fd)
  3. 再次使用stat(),查看inode是否已更改。如果是,则从位置p开始显示文件的内容
  4. 重复

相关问题 更多 >

    热门问题