c - C中的并行编程不执行指令
问题描述
我需要 C 并行编程方面的帮助,来自这张图: graph image
我写了这段代码:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int r2;
printf("--------- Program start ---------");
printf("\nBlock A instructions"); //block A
printf("\nBlock B instructions"); //block B
r2= fork();
if (r2==0){ //child
printf("\nBlock E instructions"); //block E
printf("\nBlock F instructions"); //block F
exit(0);
}
else{
if (r2>0){ //father
printf("\nBlock C instructions"); //block C
printf("\nBlock D instructions"); //block D
exit(0);
}
else printf("\nError");
}
printf("\nBlock G instructions"); //block G
printf("\nBlock H instructions"); //block H
printf("\n--------- Program finish ---------");
}
输出是:
--------- Program start ---------
Block A instructions
Block B instructions
Block E instructions
Block F instructionsBlock B instructions
Block C instructions
Block D instructions
为什么程序不写其他指令,为什么写两次“块B指令”?
- - - - - - - - - - - 编辑: - - - - - - - - - - -
新代码是:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main ()
{
printf("--------- Program start ---------\n");
printf("Block A instructions\n"); //block A
printf("Block B instructions\n"); //block B
fflush(stdout);
pid_t r2= fork();
if (r2==0){ //child
printf("Block E instructions\n"); //block E
printf("Block F instructions\n"); //block F
fflush(stdout);
exit(1);
}
else{
if (r2>0){ //father
printf("Block C instructions\n"); //block C
printf("Block D instructions\n"); //block D
fflush(stdout);
wait(NULL); //wait for child process to join with this parent, returns no value
}
else printf("Error");
}
printf("Block G instructions\n"); //block G
printf("Block H instructions\n"); //block H
printf("--------- Program finish ---------");
return 0;
}
现在的输出是:
--------- Program start ---------
Block A instructions
Block B instructions
Block E instructions
Block F instructions
Block C instructions
Block D instructions
Block G instructions
Block H instructions
--------- Program finish ---------
有时 C 和 D 指令写在 E 和 F 指令之前,这是正常的还是应该总是 EF --> CD ?顺便说一句,代码好还是有一些错误?我用 -Wall 编译它,但没有收到任何错误消息
解决方案
<stdio.h>
被缓冲,见stdio(3)和setvbuf(3)。您应该在适当的地方调用fflush(3) ,特别是在fork(2)之前。
顺便说一句,您的标准 libc 的代码是free software,可能是GNU glibc。当然它使用syscalls(2)。所以你应该研究它的源代码。
另请阅读如何调试小程序
printf("\nBlock C instructions");
容易出错。可以刷新缓冲区,\n
实际上应该用作printf(3)控制格式字符串的最后一个字符。
推荐阅读
- php - 如何将数据发送到服务器?
- c++ - 如何在 sublime text 3 中编译多个文件
- python - 为什么这会出错而这不会?
- typescript - 使用打字稿在 pixi.js 中创建位图文本时出错
- java - Spark 2.3 java udf 是否需要在应用程序的每个java类中注册?
- jquery - 实现在可排序函数中抓取多个项目(JQuery)
- codeigniter - 如何通过仅在类中声明来在每个方法中使用会话变量
- c# - 如何在 MVC 中使用 Windows 身份验证存储每个用户的属性
- tableau-api - 使用日期参数将 Tableau 仪表板默认设置为昨天
- r - 修复使用 mutate 函数和 ggplot 时 X 标签的顺序