我正在研究操作系统,但无法真正掌握这段代码:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int pid;
int i;
pid = fork();
switch(pid)
{
case -1:
perror ("Error \n");
break;
case 0:
for(i=1; i < 11; i++)
printf ("Im the son %d, My father is %d - Loop %d \n", getpid(), getppid(), i);
break;
default:
for(i=1; i < 11; i++)
printf ("Im the father %d and my father is %d - Loop %d \n", getpid(), getppid(), i);
wait(NULL);
printf("End of the father process %d - My son process %d have finished.\n", getpid(), pid);
break;
}
}
我知道你 fork (创建进程的副本),如果一切顺利(与-1不同),那么它会在 for
中循环十次,然后中断,我不明白这就是儿子如何返回到 for
的方式,我的意思是,如果它是 0(儿子),则 printf“它是儿子 X,我的父亲是 Y”,然后中断。怎么两个都循环了10次?.
最佳答案
不带 {}
的
for()
仅重复执行下一行。
for(i=1; i < 11; i++)
printf();
break;
与
相同for(i=1; i < 11; i++) {
printf();
}
break;
关于C进程和fork进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578823/