[PLUG] Weird Output of a C program in Linux

Devendra Laulkar devendralaulkar at gmail.com
Tue Jul 17 15:49:35 IST 2007


Hi,


On 7/17/07, Ashutosh Adkar <ashu.adkar at gmail.com> wrote:
>
> int main ()
> {
> printf ("Hello World!");
> if (fork == 0)
>      printf ("I'm the child!\n");
> else
>      printf ("I'm the parent!\n");
> }
>
> The output of the above program is :
>
> Hello World!I'm the child!
> Hello World!I'm the parent!


How did you get the output ? I don't think that the above program will
compile at all, with fork being undeclared.
If its calling fork() - then your guess is right, when you append the
newline character, the buffer is flushed and "Hello World!" is printed
before the fork call.

If you want to see this -You can experiment with fflush() or use gdb.

Eg>
devendra:$ gcc test.c  -g
devendra:$ gdb a.out
GNU gdb 6.5
(gdb) b main
Breakpoint 1 at 0x80483f0: file test.c, line 5.
(gdb) r
Starting program: /home/devendra/a.out

Breakpoint 1, main () at test.c:5
5         printf ("Hello World!\n");
(gdb) n
Hello World!    <--  The buffer is cleared
6         if (fork() == 0)
(gdb) c


-Devendra Laulkar.



More information about the Plug-mail mailing list