I have a program that runs fine once. It takes in text from an input file, switches the capitalization (lower becomes upper and vice versa), and outputs the text into an output file.
The problem occurs when I try to loop the pipeline by throwing the whole thing, or parts of the forks in a while loop but nothing seem to work. Help
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
FILE *in, *out;
char buff[100];
int p1[2], p2[2];
in = fopen("input.txt", "r");
out = fopen("output.txt", "w");
while(!feof(in)){
fgets(buff, 100, (FILE*)in);
pid_t f1;
if (pipe(p1)==-1 || pipe(p2)==-1){
printf("Pipe Failed\n");
return 1;
}
f1 = fork();
if(f1 < 0){
printf("fork Failed\n");
return 1;
}
else if (f1 > 0){
close(p1[0]);
int count = 1;
in = fopen("input.txt", "r");
while(!feof(in)){
fgets(buff, 100, (FILE*)in);
printf("Round %d with %s", count, buff);
write(p1[1], buff, 100);
close(p1[1]);
wait(NULL);
count++;
}
}
else {
pid_t f2 = fork();
if (f2 < 0){
printf("fork Failed\n");
}
else if (f2 > 0){ //reverse letters
close(p1[1]); //closes writing of pipe1
char temp[100] = "start", rev[100], tst[100] = "not";
int i;
while(strcmp(tst, temp) != 0){
strncpy(tst, temp, 100);
read(p1[0], temp, 100);
printf("Reversing %s or %s", temp, tst);
for(i=0; i<strlen(temp); i++){
if(temp[i]=='\0') break;
else{
if(isupper(temp[i])) rev[i] = tolower(temp[i]);
else rev[i] = toupper(temp[i]);
}
}
rev[i] = '\0';
close(p1[0]);
close(p2[0]);
write(p2[1], rev, strlen(temp)+1);
close(p2[1]);
wait(NULL);
}
}
else { //output file
close(p2[1]);
char result[100]="start", tst[100]="not";
while(strcmp(tst, result) != 0){
strncpy(tst, result, 100);
read(p2[0], result, 100);
fputs(result, out);
close(p2[0]);
wait(NULL);
}
exit(0);
}
exit(0);
}
}
fclose(in);
fclose(out);
return 0;
};
I've tried putting the while(!feof(in)) around the entire program, and the version that I posted.