Can somebody explain to me why these two similar codes (except for the \n
position) result in different output:
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
int main()
{
int pid, i=0;
printf("Ready to fork\n");
pid=fork();
if (pid==0)
{
printf("Child starts\n");
for (i=0; i<1000; i++);
printf("Child ends\n");
}
else
{
wait(0);
for (i=0; i<1000; i++);
printf("Parent process ends\n");
}
return 1;
}
Output:
And this:
#include <unistd.h>
#include<sys/wait.h>
#include <stdio.h>
int main()
{
int pid, i=0;
printf("\nReady to fork %d", getpid());
pid=fork();
if (pid==0)
{
printf("\nChild starts %d",getpid());
for (i=0; i<1000; i++);
printf("\nChild ends %d", getpid());
}
else
{
wait(0);
for (i=0; i<1000; i++);
printf("\nParent process ends %d", getpid());
}
return 1;
}
Results in:
I really can’t find any satisfactory reason of why a simple change in the position of \n
changes the output of the program at the level where the parent program seems to restart after fork execution completes.
Thank you in advance.