0

I have a C program that can pipe multiples processes together here's a running example:

./a.out cat test ; grep left ; wc -c

It basically pipes the output of cat test to grep left and grep left to wc -c

I want to add a function that will copy the number of bytes of the output in a .txt file before piping the output. this is the way I pipe the output and the code for the file that I tried:

      int bytes;
      for(bytes = 0; getc(stdout) != EOF; ++bytes);
      
      FILE *f=fopen("count","w");
      fprintf(f, "%d : %d\n", i, bytes);
      fclose(f);
      //stdout
      if (execlp("/bin/sh","sh","-c",tabCommande[i], (char *)NULL) == -1) {
            error_and_exit();
      }

After using my code it only writes the last output in the file but only rights 0 for example. If I pipe 3 processes, it will write 3 : 0

If someone can help me find the issue I would really appreciate it.

ryyker
  • 22,849
  • 3
  • 43
  • 87
  • 1
    If your command line is executed by a shell, you run `a.out` with two arguments — `cat` and `test`. The `;` marks the end of the command; `grep left` runs, waiting for terminal input, and then `wc -c` runs, also waiting for terminal input. It isn't clear what else is going on here, or is meant to be going on here. – Jonathan Leffler Dec 06 '21 at 16:14
  • As mentioned above `;` marks the end of a command in the shell that you are using to run `./a.out`. You can quote the `;` as `";"` or `';'` to pass it as a command line argument of `./a.out`. (You can also escape the `;` with a backslash like ``\;`` to achieve the same thing.) – Ian Abbott Dec 06 '21 at 16:51
  • But do you know how to count the output of stdout before pipping ? – BrokenStarz111 Dec 06 '21 at 16:55
  • `getc` reads from an *input* stream, but `stdout` is an *output* stream, so `getc(stdout)` is wrong. – Ian Abbott Dec 06 '21 at 16:59
  • its seems a bit of a chicken and egg problem, as piping would be initiated in `stdin` _after_ the count of `stdin` items occurs. – ryyker Dec 06 '21 at 17:16
  • Your code could [open pipes to stdin and stdout along with an output file](https://codereview.stackexchange.com/questions/162546/send-command-and-get-response-from-windows-cmd-prompt-silently) to completely encapsulate this sequence of requirements. – ryyker Dec 06 '21 at 17:46

0 Answers0