Hi all,
I was reading Vijaya Mukhi's The 'C' Odyssey UNIX - The Open-Boundless C (1st ed.). This is in reference to program 43 in the first chapter when file buffering is introduced.
#include <stdio.h>
int main() {
FILE *fp;
char buff[11];
int pid;
fp=fopen("baby1","r");
pid=fork();
if(!pid) {
printf("initial file handle :: %d\n",ftell(fp));
fread(buff,sizeof(buff),1,fp);
buff[10]='\0';
printf("child read :: %s\n",buff);
printf("child file handle :: %d\n",ftell(fp));
}
else {
wait((int *)0);
printf("parent file handle :: %d\n",ftell(fp));
fread(buff,sizeof(buff),1,fp);
buff[10]='\0';
printf("parent read :: %s\n",buff);
printf("end file handle :: %d\n",ftell(fp));
}
return 0;
}
The contents of baby1 are:
abcdefghijklmnopqrstuvwxyz
As per the book, the output should be:
initial file handle :: 0
child read :: abcdefghij
child file handle :: 11
parent file handle :: 1024
parent read ::
end file handle :: 1024
The book explains this by saying that fread() reads 1024 characters (whatever the block size is) by default into a buffer. Hence the file pointer also moves by 1024 bytes which is reflected because the process is different.
I tried the same code on Solaris and RHEL and got interesting results.
Output on Solaris:
initial file handle :: 0
child read :: abcdefghij
child file handle :: 11
parent file handle :: 11
parent read :: lmnopqrstu
end file handle :: 22
This indicates that in Solaris, block size is the same as specified in the fread() arguments. There is no such thing called default block size.
Output on RHEL:
initial file handle :: 0
child read :: abcdefghij
child file handle :: 11
parent file handle :: 26
parent read :: ΒΈ
end file handle :: 26
This indicates that in RHEL, block size is a number greater than 26 but the file pointer never exceeds the size of file.
From what I understood, across various OS'es system calls are different but library calls behave in the same way. Library calls should be system independent which is not the case here. I would like some clarification on this point.
I would also like to have some idea of how the file buffering takes place internally in case of system calls and library calls.
Thanks in advance.