c - 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);
...
如果您\n
在父级的 printf 中包含 ,这会导致(在某些情况下)输出缓冲区被刷新,以便在您调用时它是空fork
的,并且子级不会写入附加数据。请注意,如果您将输出重定向到文件,您可能会得到不同的行为,因为\n
在这种情况下可能不会导致刷新。如果要确保在任何给定点刷新缓冲区,请调用fflush
.
推荐阅读
- android - android导航视图之前(左侧)菜单项的空白空间
- angular - 无法让 resetStyle 在 ngx-leaflet 中工作
- php - PHP mysqli echo 相关链接按类别
- javascript - 在文件夹中插入图像在控制器中显示空值
- android - 如何使用旧名称重定向到商店中的应用程序?
- sap - 了解数据安全配置文件的外观
- git - 如何将另一个文件添加到我的拉取请求中?
- sql - Presto 中按 id 和按月份的累计金额
- amazon-web-services - ElasticSearch 不会返回嵌套查询的命中
- android - Android BLE onConnectionUpdated()