Im trying to make 3 processes with fork but I keep getting segmentation fault and dont know why. I just started using fork() so Im not sure if this is correct.
Code:
#include <stdio.h>
int main()
{
FILE *Rfp,*Wfp;
char s[40];
if(fork()==0){ //10
if(fork()==0){ //Grandchild
Rfp = fopen("File3.txt","r");
if(!Rfp){exit(1);
}
else{
while(fgets(s,20,Rfp)!=NULL){
printf("Grandchild: %s\n",s); //20
}
fclose(Rfp);
}
}
else{ //Child
Rfp = fopen("File2.txt","r");
//Wfp = fopen("Fiel3.txt","w"); //30
if(!Rfp){exit(1);
}
else{
while(fgets(s,20,Rfp)!=NULL){
printf("Child: %s\n",s);
// fputc();
}
//40
fclose(Rfp);
fclose(Wfp);
}
}
}
//-----------------------------------------------------------------
else{ //Parent //50
Rfp = fopen("File1.txt","r");
// Wfp = fopen("File2.txt","w");
if(!Rfp)exit(1);
else{
while(fgets(s,20,Rfp)!=NULL){
printf("Parent: %s\n",s);
//fputc();
}
fclose(Rfp);
fclose(Wfp);
}
}
return 0;
}