【发布时间】: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将位于持久的“真实”文件系统上,例如XFS或ext4。sysfsis nothing like that.