在 Windows 上使用 Cygwin,我想在服务器日志中发出特定消息的声音通知。我写了以下内容:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f = fopen("/dev/stdin", "r");
char bar=' ';
if(f==NULL) {
return 1;
}
do {
bar = fgetc(f);
if((bar=='\n') || (bar=='\r')) {
printf("\a");
}
if(bar!=EOF) {
printf("%c", bar);
}
} while(bar!=EOF);
fclose(f);
printf("Done.\n");
return 0;
}
然后我运行了以下命令:
tail -f serverlog | grep myMessage | ./alerty.exe
有时我会收到通知,有时我不会。
我的问题有两个: 1) 在我的 C 程序中,什么是错误的?为什么我不能始终如一地读取管道输入?这激起了我的好奇心,所以我非常想知道。
2) 当特定文本出现在文件中时,如何实现让我的系统发出蜂鸣声的最初目标?
最佳答案
- 默认情况下,如果 stdin/stdout 是终端的,则它们是行缓冲的,否则是 block 缓冲的。这不仅会影响您的程序(实际上 gets 会在可用且您正在打印行时立即返回),还会影响 grep。它需要
--line-buffered
标志。 Sed 应该能够为您完成这项工作。尝试一下:
tail -f 服务器日志 | sed -une 's/myMessage/\a&/p'
(
-u
设置无缓冲——希望 cygwin 支持它——我正在检查 Linux)
关于Cygwin 读取从 tail -f 输入的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4902166/