ido kahana
ido kahana

Reputation: 165

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?

Upvotes: 2

Views: 408

Answers (2)

LearningC
LearningC

Reputation: 3162

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;
}

Upvotes: 6

eqwert
eqwert

Reputation: 507

When you are executing your program, fork creates a new process and continues execution at the point that you call fork().

So when you reach fork(), the program has already called printf("Hello, world! \n");, and both the parent and child processes just return 0; and the program finished execution.

If you just want to print "Hello world" forever, just do:

while(true) {
    printf("Hello, world! \n");
}

If you wanted to make a fork bomb (bad):

while(true) {
    fork();
    printf("Hello, world! \n");
}

I wouldn't recommend running this code, as its unsafe and will probably crash your terminal/computer.

Upvotes: 6

Related Questions