问题
I need to write a C program (myprogram
) which checks output of other programs. It should basically work like this:
./otherprogram | ./myprogram
But I could not find how to read line-by-line from stdout
(or the pipe), and then write all this to stdout
.
回答1:
Create an executable using:
#include <stdio.h>
int main()
{
char line[BUFSIZ];
while ( fgets(line, BUFSIZ, stdin) != NULL )
{
// Do something with the line of text
}
}
Then you can pipe the output of any program to it, read the contents line by line, do something with each line of text.
回答2:
One program's stdout
becomes the next program's stdin
. Just read from stdin
and you will be fine.
The shell, when it runs myprogram
, will connect everything for you.
BTW, here is the bash code responsible: http://git.savannah.gnu.org/cgit/bash.git/tree/execute_cmd.c
Look for execute_pipeline
. No, the code is not easy to follow, but it fully explains it.
来源:https://stackoverflow.com/questions/24214038/how-to-read-from-stdout-in-c