<分区>
有人可以向我解释为什么这两个相似的代码(\n
位置除外)会导致不同的输出:
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
int main()
{
int pid, i=0;
printf("Ready to fork\n");
pid=fork();
if (pid==0)
{
printf("Child starts\n");
for (i=0; i<1000; i++);
printf("Child ends\n");
}
else
{
wait(0);
for (i=0; i<1000; i++);
printf("Parent process ends\n");
}
return 1;
}
输出:
还有这个:
#include <unistd.h>
#include<sys/wait.h>
#include <stdio.h>
int main()
{
int pid, i=0;
printf("\nReady to fork %d", getpid());
pid=fork();
if (pid==0)
{
printf("\nChild starts %d",getpid());
for (i=0; i<1000; i++);
printf("\nChild ends %d", getpid());
}
else
{
wait(0);
for (i=0; i<1000; i++);
printf("\nParent process ends %d", getpid());
}
return 1;
}
结果:
我真的找不到任何令人满意的理由来说明为什么对 \n
位置的简单更改会在父程序似乎在 fork 执行完成后重新启动的级别更改程序的输出.
提前谢谢你。