Ben
Ben

Reputation: 2465

C strange anomaly, when writing to file (works normally when writing to stdout)

I'm very new to C so please bear with me. I am struggling with this for really long time and I had a hard time to narrow down the cause of error.

I noticed that when forking process and writing to a file (only the original process writes to the file a strange thing happens, the output is nearly multiplied by the number of forks, hard to explain, thus I made a small test code where you can run and it recreates the problem.

#include <stdio.h>
#include <stdlib.h>


void foo()
{
  FILE* file = fopen("test", "w");
  int i=3;
  int pid;
  while (i>0)
  {
    pid=fork();
    if(pid==0)
    {
      printf("Child\n");
      exit(0);
     }
    else if(pid > 0)
    {
      fputs("test\n", file);
      i=i-1;
     }
 }

}

int main()
{
  foo();
  exit(EXIT_SUCCESS);
}

Compile and run it once the way it is and once with file=stdout. When writing to stdout the output is:

test
test
test

But when writing to the file the output is:

test
test
test
test
test
test

Also if you add indexing and change i to a larger number you can see some kind of a pattern, but that doesn't help me.

Well frankly said I have no idea why could this happen, neither how to fix it. But I am a total novice at C so there might be just a normal logical explanation for all this =).

Thank you for all your time and answers.

Upvotes: 5

Views: 122

Answers (1)

geekosaur
geekosaur

Reputation: 61457

stdout is usually unbuffered or line buffered; other files are typically block buffered. You need to fflush() them before fork(), or every child will flush its own copy of the buffer, leading to this multiplication.

Upvotes: 8

Related Questions