I created a simple fork program in c
printf("first");
fork();
printf("second");
I learnt that fork function creates a child process that executes from the next instruction which should be like
firstsecondsecond
but the output i got is
firstsecondfirstsecond
Am i wrong?
Remember that output to stdout
(which is where printf
writes) is buffered. More specifically it's by default (when output is to a terminal) line-buffered, meaning that the buffer is flushed on newline.
Now what happens here is that the first printf
call writes "first"
to the output buffer, but it's not flushed. Then you fork, which creates an exact duplicate of the process, including the stdout
buffer. Then both processes prints "second"
.
After that, presumably, both processes ends which causes stdout
to be flushed and closed. This flushes the contents of the buffers in both processes, which will contain the exact same data, leading to the output you get.
If you explicitly flush the buffer before calling fork
(for example by printing a newline or calling fflush(stdout)
) the behavior should be as you expect.