The file is available to both the processes after the fork call.
So most likely one of the process reads the file & the file offset is
updated , and the other process gets an EOF .
So only one process prints the contents .
May get the desired result with read system call since you can control the
number of bytes to be read .
Or may try with setting the buffering options with setbuf function.
i really can't use read do to the fact that i want it to read a whole line and all the lines aren't the same length. i got it to work using read but it didn't complete my objective to read line by line.
And i don't understand why one process gets an EOF. I thought they shared the same pointer?
this is what i have now still no idea why is doesn't work
#include <stdio.h>
#include <fcntl.h>
main( )
{
FILE *fileptr;
char temp1[100];
char buff2[20];
int pid2;
FILE * fileptr1;
fileptr1 = fopen("file1.txt","rt");
pid2=fork();
printf("%i",getpid());
printf("just created \n");
while(1)
{
printf("%i",getpid());
printf("in the while loop\n");
fscanf(fileptr1,"%s",temp1);
if(feof(fileptr1)==0)
{
printf("%i",getpid()); //id of current process
printf(" Read: ");
printf("%s",temp1); //what was just read
printf("\n");
sleep(5);
}
else
break;
}
}
this was the output
26017just created
26017in the while loop
26017 Read: m+n
26016just created
26016in the while loop
26017in the while loop
26017 Read: o+p
26017in the while loop
26017 Read: q+r+s
26017in the while loop
26017 Read: a+b+c+d
26017in the while loop