Thanks sree_ec. This is the code I experimented on. It is derived from the code posted there.
#include<stdio.h>
#include<unistd.h>
int main()
{
FILE *fp;
char buff[11];
int pid, i;
fp=fopen("vivek","w+");
for(i=0;i<8192;i++)
fprintf(fp,"A");
for(i=0;i<8192;i++)
fprintf(fp,"B");
for(i=0;i<8192;i++)
fprintf(fp,"C");
for(i=0;i<8192;i++)
fprintf(fp,"D");
fclose(fp);
fopen("vivek","r");
printf("M0 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR), buff);
pid=fork();
if(pid==0)
{
printf("C1 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR),buff);
fread(buff,sizeof(buff),1,fp);
buff[10]='\0';
printf("C2 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR),buff);
sleep(2);
printf("C5 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR),buff);
fread(buff, sizeof(buff),1,fp);
buff[10]='\0';
printf("C6 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR), buff);
_exit(0);
}
else
{
sleep(1);
printf("P3 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR),buff);
fread(buff,sizeof(buff),1,fp);
buff[10]='\0';
printf("P4 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR),buff);
sleep(3);
printf("P7 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR),buff);
fread(buff,sizeof(buff),1,fp);
buff[10]='\0';
printf("P8 ftell-> %ld lseek-> %ld buff-> %s\n",ftell(fp),lseek(fileno(fp),01, SEEK_CUR),buff);
_exit(0);
}
}
The output is:
M0 ftell-> 0 lseek-> 1 buff->
C1 ftell-> 1 lseek-> 2 buff->
C2 ftell-> 13 lseek-> 8195 buff-> AAAAAAAAAA
P3 ftell-> 8195 lseek-> 8196 buff->
P4 ftell-> 8207 lseek-> 16389 buff-> BBBBBBBBBB
C5 ftell-> 8208 lseek-> 16390 buff-> AAAAAAAAAA
C6 ftell-> 8220 lseek-> 16391 buff-> AAAAAAAAAA
P7 ftell-> 8210 lseek-> 16392 buff-> BBBBBBBBBB
P8 ftell-> 8222 lseek-> 16393 buff-> BBBBBBBBBB
This output helped me understand the behaviors satisfactorily.
Thanks all for the help. I highly appreciate it.
Still I would like to state an interesting conclusion
The high-level call fread() is buffered. By default, it reads a block of data …