1

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 printffunction 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.

T-D
  • 373
  • 8
  • 21

1 Answers1

3

The file handle stdout (which is used by printf) is by default line buffered, which means output using printf will be flushed (and shown in the console) either when there's a newline or when the buffer is full.

As fork creates an exact duplicate of the parent process, both processes have the same contents in the (un-flushed) output buffer, and both will be flushed when the two processes exits.

So yes you're correct in your guessing.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Great. So even though the forking is happening after the `printf`, the `stdout` buffer is still being copied since the child process is a duplicate or a clone that shares most of the parents data (including stack, heap, text etc.. ). Thanks for your clarification. – T-D Mar 16 '15 at 19:26