Cygwin 读取从 tail -f 输入的输入
在 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) 如何实现当文件中出现特定文本时让系统发出蜂鸣声的最初目标?
Using Cygwin on Windows, I wanted to have an audible notification of specific messages in a server's log. I wrote the following:
#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;
}
I then ran the following command:
tail -f serverlog | grep myMessage | ./alerty.exe
Sometimes I get notices and sometimes I don't.
My questions are two-fold:
1) What, in my C program, is wrong? Why can't I consistently read the piped input? It's piqued my curiosity so I'm desperate to know.
2) How do I accomplish the original goal of making my system beep as specific text appears in a file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
--line-buffered
标志。Sed 应该能够为您完成这项工作。尝试一下:
tail -f 服务器日志 | sed -une 's/myMessage/\a&/p'
(
-u
设置无缓冲——希望 cygwin 支持它——我正在 Linux 上检查)--line-buffered
flag.Sed should be able to do the work for you. Try just:
tail -f serverlog | sed -une 's/myMessage/\a&/p'
(
-u
sets unbuffered—hopefuly cygwin supports it—I am checking on Linux)stdout
默认情况下会进行缓冲,因此输出不一定会立即出现。尝试在printf("\a")
之后插入fflush(stdout)
。正如 Jan 提到的,您也可能会遇到标准输入的缓冲问题。
grep
有一个可能有帮助的
--line-buffered
选项。 (tail -f
会自行执行此操作,因此您无需担心。)stdout
is buffered by default, so the output won't necessarily appear immediately. Try inserting afflush(stdout)
right after yourprintf("\a")
.As Jan mentions, you also may be running into buffering issues on stdin.
grep
hasa
--line-buffered
option that might help. (tail -f
does this on its own, so you shouldn't need to worry about it.)