Reputation: 376
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 :
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:
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 :
So can anyone confirm this, and explain me why is this happening, or just a bug on my system ?
Upvotes: 3
Views: 273
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