Soumyadeep Ghosh
Soumyadeep Ghosh

Reputation: 376

Does fork() work differently on Ubuntu in Comparison to other Linux Distribution?

Ok, so here is the initial Code I was working with on an Ubuntu 17.10.

#include <unistd.h>
#include <stdio.h>
void main()
{
   printf("Demonstrating fork():\n");
   fork();
   printf("After fork():\nProcess Id is %d\n", getpid());
}

So at this stage I found out the output to be : Initial Output

So yeah I executed twice to confirm it. But later I noticed that in Online GCC Compilers and on RedHat in my College Campus, The output is pretty different:

other gcc output

Now as per my knowledge, the fork() creates another instance of the process it is called from. But in Ubuntu it seems it copies from the point where it is introduced in the code, and rather the whole Process. To detect it, I slightly chaged the code to :

#include <unistd.h>
#include <stdio.h>
void main()
{
    fork();
    printf("Demonstrating fork():\n");
    printf("After fork():\nProcess Id is %d\n", getpid());
}

And to my surprise I was right on my observation with the output :

After Change Output

So can anyone confirm this, and explain me why is this happening, or just a bug on my system ?

Upvotes: 3

Views: 273

Answers (1)

jfMR
jfMR

Reputation: 24738

But later I noticed that in Online GCC Compilers and on RedHat in my College Campus, The output is pretty different.

It has to do with the user-space buffer printf() uses.

If the program is executed at the terminal and the output is not redirected to a file, then the buffer is flushed by printf()ing \n.

The online version does not flush the buffer by printf()ing a \n because it is using another flushing policy (e.g.: the output is probably being redirected to a file).

Upvotes: 9

Related Questions