I implemented the following two pieces of code. Why is the number of printf executions in the two pieces of code not equal, one is 6 times and the other is 8 times? My system and GCC version information is as follows:
root#lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 18.04.6 LTS
Release: 18.04
Codename: bionic
root#gcc --version
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
code 1:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int i = 0;
for (;i < 2; i++)
{
fork();
printf(" i = %d\n", i);
}
return 0;
}
root#gcc test_fork.c
root#./a.out
i = 0
i = 1
i = 0
i = 1
i = 1
root# i = 1
code 2:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int i = 0;
for (;i < 2; i++)
{
fork();
printf("=");
}
return 0;
}
root#gcc test_fork.c
root#./a.out
========