Thursday, July 16, 2009

see the difference...

hii frnds..
now a interesting thing about the buffer used at the terminal on unix..

suppose the following C code is running on any unix system..

$ cat test.c

#include
int main()
{
printf("Hello\n");
if(fork()==0)
printf("World\n");
return 0;
}

$ gcc test.c
$ ./a.out
Hello
World
$ ./a.out>test
Hello
World
Hello
$

why output is different in two cases..

It is the difference between the buffer used for terminal standard output and the other ordinary file..if output is to be be shown on the terminal line buffer is used i.e. when it encounters '\n' it flushes out buffer content..but in case of other file buffer content is flushed out only when it is full..in the above code..that's why when child is run Hello is retained there in buffer and Hello is printed twice in case when output is redirected to file.But when it runs directly Hello is printed only one time..as there is '/n' which flushes out the buffer content.So Hello is printed only when parent is running..when '\n' is ommited..output will be same in both cases.Try it yourself.

Thank you...

No comments:

Post a Comment