【发布时间】:2018-08-12 06:11:49
【问题描述】:
有人可以向我解释为什么这两个相似的代码(\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 执行完成后父程序似乎重新启动的级别更改程序的输出。
提前谢谢你。
【问题讨论】:
-
您可以格式化您的代码,以便其他人阅读。而且,
'\n'通常位于末尾。输出没有变化。 -
@IharobAlAsimi:输出没有变化是什么意思?整个问题询问为什么输出有变化。它显示了改变的输出。
-
我不会阅读那个未格式化的代码,但可能与fork() in c using printf重复
-
现在看到了,只是一开始没注意。
-
@LưuVĩnhPhúc 是的,重复