I have the following 2 sets of code that output differently. [outputting to the terminal]
Code 1:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main ()
{
printf("before the fork\n");
fflush(stdout);
int pid=fork();
printf("after the fork\n");
if (pid == 0)
{
sleep(1);
printf("I'm child");
}
else
{
wait();
printf ("I'm parent");
}
exit(0);
}
Output 1:
before the fork
after the fork
after the fork
I'm child
Now only the printf after the fork is commented and we see the printf after wait() for the parent process works as expected.
Code 2:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main ()
{
printf("before the fork\n");
fflush(stdout);
int pid=fork();
// printf("after the fork\n");
if (pid == 0)
{
sleep(1);
printf("I'm child");
}
else
{
wait();
printf ("I'm parent");
}
exit(0);
}
Output 2:
before the fork
I'm childI'm parent
I am confused as in how the printf after the fork() messes up the output.
Note the following output too
Code 3:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main ()
{
printf("before the fork\n");
fflush(stdout);
int pid=fork();
printf("after the fork\n");
if (pid == 0)
{
sleep(1);
printf("I'm child");
}
else
{
//wait();
printf ("I'm parent");
}
exit(0);
}
Output 3:
before the fork
after the fork
I'm parentafter the fork
I'm child
Any idea why this discrepancy?