c中多进程的输出有什么问题?
What 's problem of the output in multiple process in c?
我有以下代码:
int main()
{
for (int i = 0; i < 3; i++) {
int t = fork();
if (t == 0) {
printf("child %d id: %ld from pid: %ld\n", i, (long)getpid(), (long)getppid());
exit(0);
}
else if (t > 0) {
wait(NULL);
printf("father %d id: %ld from pid: %ld\n", i, (long)getpid(), (long)getppid());
}
}
return(0);
}
当我运行时输出是:
而当我在 t>0 时删除 printf 中的“\n”时,输出为:
第二个输出如何比第一个输出更多?请!!
抱歉,我意识到这是关于 C 中缓冲区的问题,我只是在我的多线程分配中遇到这个问题,而我是 C 中的新手,还不知道这个问题。我只是认为它来自多线程的问题所以我在这里问。
您需要记住 printf
不一定会导致写入任何数据。相反,printf
只是将数据写入根据需要刷新的内部缓冲区。
让我们稍微简化一下代码并展开循环来检查发生了什么
int
main(void)
{
int t, i = 0;
t = fork();
if( t == 0 ) {
printf("child %d id: %ld from pid: %ld\n",
i, (long)getpid(), (long)getppid());
exit(0);
} else if( t > 0 ) {
wait(NULL);
printf("parent %d id: %ld from pid: %ld",
i, (long)getpid(), (long)getppid());
}
/* The output buffer now contains "parent N id ..."
but the parent has not yet written any data. */
i += 1;
t = fork();
if( t == 0 ) {
/* Here, the output buffer still contains "parent N id ..." */
printf("child %d id: %ld from pid: %ld\n",
i, (long)getpid(), (long)getppid());
/* The newline above causes the buffer to be flushed,
so now this child writes "parent N id ...child M id: ..." */
exit(0);
...
如果您在父级的 printf 中包含 \n
,这会导致(在某些情况下)刷新输出缓冲区,以便在您调用 fork
时输出缓冲区为空,而子级不会写入附加数据。请注意,如果您将输出重定向到一个文件,您可能会得到不同的行为,因为 \n
在这种情况下可能不会导致刷新。如果要确保在任何给定点刷新缓冲区,请调用 fflush
.
我有以下代码:
int main()
{
for (int i = 0; i < 3; i++) {
int t = fork();
if (t == 0) {
printf("child %d id: %ld from pid: %ld\n", i, (long)getpid(), (long)getppid());
exit(0);
}
else if (t > 0) {
wait(NULL);
printf("father %d id: %ld from pid: %ld\n", i, (long)getpid(), (long)getppid());
}
}
return(0);
}
当我运行时输出是:
而当我在 t>0 时删除 printf 中的“\n”时,输出为:
第二个输出如何比第一个输出更多?请!!
抱歉,我意识到这是关于 C 中缓冲区的问题,我只是在我的多线程分配中遇到这个问题,而我是 C 中的新手,还不知道这个问题。我只是认为它来自多线程的问题所以我在这里问。
您需要记住 printf
不一定会导致写入任何数据。相反,printf
只是将数据写入根据需要刷新的内部缓冲区。
让我们稍微简化一下代码并展开循环来检查发生了什么
int
main(void)
{
int t, i = 0;
t = fork();
if( t == 0 ) {
printf("child %d id: %ld from pid: %ld\n",
i, (long)getpid(), (long)getppid());
exit(0);
} else if( t > 0 ) {
wait(NULL);
printf("parent %d id: %ld from pid: %ld",
i, (long)getpid(), (long)getppid());
}
/* The output buffer now contains "parent N id ..."
but the parent has not yet written any data. */
i += 1;
t = fork();
if( t == 0 ) {
/* Here, the output buffer still contains "parent N id ..." */
printf("child %d id: %ld from pid: %ld\n",
i, (long)getpid(), (long)getppid());
/* The newline above causes the buffer to be flushed,
so now this child writes "parent N id ...child M id: ..." */
exit(0);
...
如果您在父级的 printf 中包含 \n
,这会导致(在某些情况下)刷新输出缓冲区,以便在您调用 fork
时输出缓冲区为空,而子级不会写入附加数据。请注意,如果您将输出重定向到一个文件,您可能会得到不同的行为,因为 \n
在这种情况下可能不会导致刷新。如果要确保在任何给定点刷新缓冲区,请调用 fflush
.