All. It is straightforward from the code. No exit()
is called in any created child and they are free to execute what parent executes. So each child executes printf()
once. This can be programmatically verified as below:
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
printf("PID = %d
", getpid());
for(int i=0;i<3;i++)
{
if (fork() == 0)
printf("PID = %d
", getpid());
}
while(wait(NULL)>0);
printf("PID: %d finished
", getpid());
}
OUTPUT
$ ./a.out
PID = 120360
PID = 120361
PID = 120362
PID = 120364
PID = 120363
PID = 120366
PID: 120363 finished
PID: 120366 finished
PID = 120367
PID = 120365
PID: 120367 finished
PID: 120365 finished
PID: 120362 finished
PID: 120364 finished
PID: 120361 finished
PID: 120360 finished
From the above output, it can be seen that each created child is executing printf()
once.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…