2

I am trying to understand why the output of this program always starts with 012xxxxxxx Here is the code:

int main() {

int i;
for (i=0; i<2; i++) {
    fork();
    printf("%d", i);
}
printf("2");

}

I sketched the process graph:

enter image description here

But I don't understand how this output is possible. Could someone help me see why this is always the case.

foobar5512
  • 2,470
  • 5
  • 36
  • 52
  • You could figure it out yourself by printing the process ID along with the value of `i`. – Scott Hunter Oct 12 '16 at 00:07
  • @yellowantphil can you explain how this is a possible output, please? – foobar5512 Oct 12 '16 at 00:12
  • "output of this program always starts". You can't make that conclusion. You can only say that the "output is the same *for the times that you ran it*". In theory that is only one out of many possibilities and if you run it for enough times you can get a different result. – kaylum Oct 12 '16 at 00:16
  • This is a duplicate of "`printf` anomaly after `fork`" — but it's hard to find duplicates in the mobile app. – Jonathan Leffler Oct 12 '16 at 01:22

1 Answers1

0

A simple explanation is that the original process is faster ready to continue than the forked one(s).

So the original process triggers the forking in the OS, and then continues on, producing 0, 1, 2, and is done. Then the forked processes start and do their printing.

Note that fork() does not guarantee anything about the sequence the two processes are executed in; they will just be two independent processes in the OS. It can well be that the OS lets the first one run for another 100 CPU cycles before switching (and then it is already done).
On another OS, it could be just the other way around...

Aganju
  • 6,295
  • 1
  • 12
  • 23
  • I thought forked processes have to run concurrently with the parent process. So the main loop cannot finish before the children have at least started. – foobar5512 Oct 12 '16 at 00:19
  • 'concurrently' on a computer always means 'sequentially, with small slices of time each', each one getting a share. Multiple CPUs or cores _might_ change that, but it is the OS choice how this is handled. As long as the OS guarantees that the forked process starts with identical setup, there is no requirement to wait for it to be ready; and even if, one of them is going first anyway, so it could as well be the original one. – Aganju Oct 12 '16 at 00:20