I'm just learning how to use fork() in C and i have troubles understanding execution flow.
the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
printf("starting...\n");
int x = 100;
int rc = fork();
if (rc < 0) {
printf("unable to fork\n");
exit(-1);
} else if (rc == 0) {
x = x + 200;
printf("child x == %d\n", x);
} else {
x = x + 500;
printf("parent x == %d\n", x);
}
return 0;
}
executes as you would think it will:
user@fedora> ./main
starting...
parent x == 600
child x == 300
the strange thing happens when i remove \n from printf("starting...\n");
:
user@fedora> ./main
starting...parent x == 600
starting...child x == 300
Why when i remove \n
the "starting..." prints twice when it clearly shouldnt?
Please could you explain why in this case printf("starting...")
is executed twice?
Thank you!