bug in glibc?

David Tonhofer redhatter at m-plify.net
Fri Jan 18 16:45:51 UTC 2008


krishnaakishore at gmail.com wrote:
> Hi all,
>
> I have a query regarding the output of the following code:
>
> #include<stdio.h>
> #include<stdlib.h>
> #include<unistd.h>
> main(){
> 	int a=0;
> 	while(1){
> 		printf("XXX(%d)",++a);
> 		sleep(1);
> 		if(fork()==0){printf("\n");exit(0);}
> 		//you can remove the printf here,
> 		//its just to enhance the readability of output
>
>  	}
> }
>
> The output should actually be:
> XXX(1)
> XXX(2)
> XXX(3)
> XXX(4)
> XXX(5)
> XXX(6) (and so on)
>
> But the output actually is:
> XXX(1)
> XXX(1)XXX(2)
> XXX(1)XXX(2)XXX(3)
> XXX(1)XXX(2)XXX(3)XXX(4)
> XXX(1)XXX(2)XXX(3)XXX(4)XXX(5)
> XXX(1)XXX(2)XXX(3)XXX(4)XXX(5)XXX(6) (and so on)
>
> The fork() call is triggering the flushing the buffers but not
> clearing them. Hence the data in the buffers is getting accumulated.
> Appending a '\n' to "XXX(%d)" will generate the expected output.
>   

Isn't this working as designed? You fork the whole process, so the 
buffers are copied "as is", so the first process
prints XXX(1), the second starts off with a non-cleared XXX(1) and 
prints XXX(2) on top, yielding XXX(1)XXX(2) etc...

Just my 2 cents...






More information about the redhat-list mailing list