Cygwin 读取从 tail -f 输入的输入

标签 c windows-7 cygwin pipe

在 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) 当特定文本出现在文件中时,如何实现让我的系统发出蜂鸣声的最初目标?

最佳答案

  1. 默认情况下,如果 stdin/stdout 是终端的,则它们是行缓冲的,否则是 block 缓冲的。这不仅会影响您的程序(实际上 gets 会在可用且您正在打印行时立即返回),还会影响 grep。它需要 --line-buffered 标志。
  2. Sed 应该能够为您完成这项工作。尝试一下:

    tail -f 服务器日志 | sed -une 's/myMessage/\a&/p'

    (-u 设置无缓冲——希望 cygwin 支持它——我正在检查 Linux)

关于Cygwin 读取从 tail -f 输入的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4902166/

相关文章:

c - 数据包分层传输

windows-7 - windows 7中文件和文件夹只读属性问题

security - Windows 7 安全策略 : How Do I Allow My . NET 应用程序写入驱动器 "C:"?

c++ - 使用 Cygwin/GCC 构建 Boost 库时的名称冲突

visual-studio - 来自 Cygwin 的 "Source"VsDevCmd.bat

shell - 如何在 diff 查看器仍然打开的情况下让cleartool diff 返回到命令行?

c中的消费者生产者问题

c - 使用O_CREAT时open的执行

c++ - 如何使用 WINAPI 和 C++ 提取可执行文件的文件描述?

matlab - Mingw-w64 "Cannot download repository.txt"错误