4

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.

Gabriel Staples
  • 11,777
  • 3
  • 74
  • 108
user3155036
  • 127
  • 2
  • 10
  • 1
    You're using a `|` pipe, so `stdout` from `otherprogram1` will automatically be `stdin` for `myprogram`. That's all a pipe is - connecting an output to an input. – Marc B Jun 13 '14 at 21:32
  • 1
    Chekout `fgets` from `stdio.h`. http://www.cplusplus.com/reference/cstdio/fgets/ – R Sahu Jun 13 '14 at 21:33
  • Are you asking how to do this programmatically in c? What you have there with the | will work. – SeriousBusiness Jun 13 '14 at 21:34
  • Related: 1) [C: Run a System Command and Get Output?](https://stackoverflow.com/q/646241/4561887), 2) [How can I run an external program from C and parse its output?](https://stackoverflow.com/q/43116/4561887), 3) [Capturing stdout from a system() command optimally](https://stackoverflow.com/q/125828/4561887) and 4) [the most-thorough C++ answer] [How do I execute a command and get the output of the command within C++ using POSIX?](https://stackoverflow.com/q/478898/4561887). – Gabriel Staples Feb 01 '21 at 21:58

2 Answers2

7

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.

Gabriel Staples
  • 11,777
  • 3
  • 74
  • 108
Sean Perry
  • 3,588
  • 1
  • 14
  • 29
4

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.

Gabriel Staples
  • 11,777
  • 3
  • 74
  • 108
R Sahu
  • 196,807
  • 13
  • 136
  • 247