Cygwin read entry comes from -f tail

Using Cygwin on Windows, I wanted to receive a sound notification of specific messages in the server 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; } 

Then I ran the following command:

 tail -f serverlog | grep myMessage | ./alerty.exe 

Sometimes I get notifications, and sometimes not.

My questions are twofold: 1) What is wrong with my C program? Why can't I read the input channel all the time? It aroused my curiosity, so I desperately want to know.

2) How to fulfill the original goal of making my system sound when a certain text is displayed in a file?

+6
c windows-7 pipe cygwin
source share
2 answers
  • By default, stdin / stdout is buffered line by line if they are terminal and block buffers otherwise. This affects not only your program (in fact, get will immediately return when something is available and you print lines), but also grep . He needs the --line-buffered flag.
  • Sed should be able to work on you. Try simply:

    tail -f serverlog | sed -une 's / myMessage / \ a & / p'

    ( -u installs unbuffered - hope cygwin supports it, I check Linux)

+3
source share

stdout buffered by default, so the output will not necessarily be displayed immediately. Try pasting fflush(stdout) right after printf("\a") .

As Jan mentions, you may also encounter buffering problems on stdin. grep has a --line-buffered that can help. ( tail -f does this on its own, so you don't need to worry about it.)

+1
source share

All Articles