0

I wrote a simple example of fork() like below:

#include <sys/types.h>
void main()
{

        printf("Stack overflow\n");
        pid_t p = fork();
        if ( p )
            printf("I am parent\n");
        else
            printf("I am child\n");
        return 0;
}

Ideally, "Stack overflow" should be printed only once but at my end the string is printed twice. I am unable to understand it. Can anyone help?

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
username_4567
  • 4,737
  • 12
  • 56
  • 92
  • You might want to add `#includes` at the top of this. I'm presuming you use `unistd.h` (for fork) and `stdio.h` (for printf), but there might be other implementations you use, and these of course could change behaviour. – Marcus Müller Jul 04 '15 at 17:18

1 Answers1

1

That's a flushing problem: Your program is running just fine, but the output of the first printf is only handed over to the standard output after the fork has happened.

Try

fflush(stdout);

before forking. It fixes this.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94