【问题标题】:How do I wait on output from sysfs?如何等待 sysfs 的输出?
【发布时间】:2022-01-18 02:15:39
【问题描述】:

我尝试了明显的(见下文),但它没有捕捉到 /var/log/syslog 的新输出。我确定某个地方已经有答案了,但我一直没能找到它。

这是我的代码(我猜怎么做):

#include <stdio.h>
#include <stdlib.h>  // provides fopen()
#include <unistd.h>  // provides sleep()


int main() {

    // *** This is failing to pick up new output on /var/log/syslog. I'm not sure
    // how to do this properly.

    // Open a read file handle on /sys/kernel/tracing/trace and wait for data to
    // appear there. When it does, echo it to the screen. This is essentially an
    // implementation of "tail -f /sys/kernel/tracing/trace".

    //FILE *fp = fopen("/sys/kernel/tracing/trace", "r");
    FILE *fp = fopen("/var/log/syslog", "r");
    char c;

    if (fp != NULL) {
        printf("Opened the file successfully. Waiting...\n");
    } else {
        printf("Failed to open the file.\n");
      exit(1);
    }

    // Check every second and output whatever is in the buffer.
    while(1) {
        c = fgetc(fp);

        // We get back -1 when there is nothing to read.
        if (c != -1) {
            printf("%c", c);
        } else {
            printf(".");  fflush(stdout);
            sleep(1);
        }
    }

    fclose(fp);
    return 0;
}

【问题讨论】:

  • 看看:inotify (7)
  • 也许您只想运行tail -f /var/log/syslog 而不是编写自己的软件。如果你真的想编写自己的软件,一个想法是运行strace tail -f /var/log/syslog 看看它做了什么,或者阅读tail 的源代码。
  • /var/log/syslog 和 sysfs 有什么关系?
  • 这是一个类似的文件系统,更容易生成输出。我错过了什么吗?
  • @StackOOverflow 我错过了什么吗? 是的。 /var/log/syslog 将位于持久的“真实”文件系统上,例如 XFSext4sysfs is nothing like that.

标签: c linux


【解决方案1】:

需要调用 clearerr(fp) 来清除 feof 指标:

// Check every second and output whatever is in the buffer.
while(1) {
    c = fgetc(fp);

    // We get back -1 when there is nothing to read.
    if (c != -1) {
        printf("%c", c);
    } else {
        printf(".");  fflush(stdout); 
        if(feof(fp)) clearerr(fp);  // <-- clear the feof indicator
        sleep(1);
    }
}

【讨论】:

  • 谢谢。非常简洁并且有效。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多