1

To give you a bit of context my program basically takes commands and pipes them together and records the amount of bytes of each output in a file.

My problem is that while I managed to pipe the processes together the moment I read the output of the first (to store the bytes in a file) the second process can't read the output because the file descriptor was already used.

Is their a way to restore the file descriptor before the read or to make a back up ?

Here's a sample code in the parent the goal of this code would be to store the output in the file and restore it to before reading it :

for (int i = 1; i < processes-1; i++) {
      
   close(apipe[i][1]); 
      FILE *fp;
      fp = fopen("count", "a");
      
      char buffer[4096];
      int amount=0;
      
      int std_fd=dup(apipe[i][0]);
      int count;
      while (1) {
            count = read(std_fd, buffer, sizeof(buffer));
            amount+=count;
            if (count == -1) {
            if (errno == EINTR) {
                continue;
            } else {
                perror("read");
                exit(1);
            }
            } else if (count == 0) {
                break;
            }
            else{
                break;}
     }
      fprintf(fp, "%d : %d \n", i,amount); 
      close(apipe[i][0]);
      if(i==1){
           close(apipe[0][0]); 
           close(apipe[0][1]);  
      }
      fclose(fp); 
      
}

alinsoar
  • 15,386
  • 4
  • 57
  • 74
  • 2
    There's no simple way to do this. You can implement a child process that acts like the `tee` command. – Barmar Dec 09 '21 at 22:17
  • 1
    Hey, are you working with asmazizou? Your project looks very similar to https://stackoverflow.com/questions/70282385/copy-pipe-output-and-execute-a-command-on-it-and-save-in-a-file-all-without-sto – Barmar Dec 09 '21 at 22:20
  • Were both trying to solve the same problem but where not working on it together – BrokenStarz111 Dec 09 '21 at 22:27
  • It might be better if you worked together, so we don't have to answer so many similar questions. You also might be able to figure it out yourselves if you put your headers together. You'll learn better that way. – Barmar Dec 09 '21 at 22:28
  • @Barmar do you know if it's possible to make a copy of a file descriptor ?Like a back up – BrokenStarz111 Dec 09 '21 at 22:39
  • 1
    A file descriptor is just an integer. You mean the data that you read from it. There's no automatic way to duplicate it. You can read from it and save in a string, then write that to another pipe. – Barmar Dec 09 '21 at 22:42
  • The string can then be reused after you write it. – Barmar Dec 09 '21 at 22:43

0 Answers0