Search code examples
cfork

Why c program with fork() call not creating a infinity loop?


int main(void)
{
   printf("Hello, world! \n");
   fork();
   return 0;
}

why it is print only 2 hello worlds? if evert time when the system excute the function fork() new procces is created, it need to print "Hello, world! \n" forever?


Solution

  • This Program should be printing Hello world once. still if it prints it twice it is because the line buffer is not cleared.
    The line buffer should be cleared because there is \n in your printf.still its not cleared means this is about the platform you are using to execute the code.
    You can verify this by adding fflush(stdout) after the printf().

    int main(void)
    {
       printf("Hello, world! \n");
       fflush(stdout);
       fork();
       return 0;
    }