I was writing a multi-process program using fork()
and i bumped into a problem.
Below is a sample code reproducing the problem (without any sort of error checking):
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
printf("hello world");
fork();
}
This code prints 2 "hello world" statements (one from parent and the other from child). However this should not be the case since the printf
function call is prior to the fork()
system call.
After testing, the problem appears to be solved by the following:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
printf("hello world\n"); \\ addition of the new line character
// or by using fflush(stdout);
fork();
}
My guessing is that the printf
buffer is being copied while its not flushed, so the child process is emptying its copy of this buffer before exiting. Hence the other printf
shows.
Can anyone provide a better explanation of this issue? Or even better, correct me if i am wrong or missing something.