OpenMPI 5.0.7 从标准输入读取矩阵数据时出现数据异常的问题求助
OpenMPI 5.0.7 从标准输入读取矩阵数据时出现数据异常的问题求助
我现在在尝试用OpenMPI并行化一个从标准输入读取大文件的程序,但遇到了输入读取异常的问题:当OpenMPI运行时初始化后,程序无法正确读取stdin的输入内容,读取到的数据是错乱的,和原输入文件完全不一致。
问题背景
我的输入文件格式固定:
- 开头三个整数:第一个是矩阵的尺寸
size,后面两个是无关的随机数(本测试示例中可忽略); - 紧接着是一个
size×size的布尔矩阵:#代表true,.代表false; - 矩阵每行恰好有
size个字符,共size行,行与行之间用换行符分隔。
我写了两个极简的测试程序来复现问题:
- 非MPI版本(
read.c):直接从stdin读取内容,存入缓冲区后原样输出到stdout,重定向后输出和原输入完全一致; - MPI版本(
read_mpi.c):仅让rank 0进程执行读取和输出逻辑,但重定向后的输出文件内容错乱,和原输入差异很大。
代码片段
非MPI版本(read.c)
#include <stdio.h> #include <stdlib.h> int main() { int size, gens, ghosts; scanf("%d\n%d\n%d\n", &size, &gens, &ghosts); int *board = (int *) calloc(size * size, sizeof(int)); char ch; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { scanf(" %c", &ch); board[i * size + j] = (ch == '#'); } } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { printf("%c", board[i * size + j] ? '#' : '.'); } printf("\n"); } return 0; }
MPI版本(read_mpi.c)
#include <mpi.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int size, gens, ghosts; int rank, *board; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { scanf("%d\n%d\n%d\n", &size, &gens, &ghosts); board = (int *) calloc(size * size, sizeof(int)); } if (rank == 0) { char ch; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { scanf(" %c", &ch); board[i * size + j] = (ch == '#'); } } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { printf("%c", board[i * size + j] ? '#' : '.'); } printf("\n"); } } MPI_Finalize(); return 0; }
环境与运行命令
- 运行环境:OpenMPI 5.0.7(使用
mpicc编译)、GCC 13.3.0,运行在Ubuntu 24.04 LTS的AArch64 Docker容器中; - 编译命令:
mpicc -o read_mpi read_mpi.c gcc -o read read.c - 运行命令:
mpirun -np 4 ./read_mpi < input.txt > output_mpi.txt ./read < input.txt > output.txt
问题现象
- 非MPI版本生成的
output.txt和原输入文件input.txt完全一致; - MPI版本生成的
output_mpi.txt内容错乱,和原输入文件差异明显,说明OpenMPI运行时干扰了stdin的读取逻辑。
我的疑问
明明只有rank 0进程在执行读取和输出操作,为什么OpenMPI运行时会导致stdin读取异常?是不是OpenMPI默认对所有进程的stdin做了共享处理?该如何解决这个问题?
内容来源于stack exchange
相关产品推荐
相关产品推荐

