Reputation: 41
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);
}
Upvotes: 1
Views: 313