写入到一个输出文件在C MPI [英] Writing to an output file in c MPI
本文介绍了写入到一个输出文件在C MPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在做这个MPI code和一切几乎是工作,因为它应该,但我有麻烦的程序的输出写入文件。下面是一些code来说明我的问题。
I am working on this MPI code and everything is almost working as it should, but I am having trouble writing the output of the program to a file. Here is some code to illustrate my problem
int main(int argc, char *argv[]){
FILE *filename;
int size, my_rank;
int count =0;
int tag =99;
int limit = 5;
MPI_Init(&argc, &argv);
MPI_Status status;
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
if(my_rank ==0)
printf("Process %d started the game and initialized the counter\n\n",my_rank);
MPI_Barrier(MPI_COMM_WORLD);
if (size != 2) {//abort if the number of processes is not 2.
fprintf(stderr, "only 2 processes shall be used for %s\n", argv[0]);
MPI_Abort(MPI_COMM_WORLD, 1);
}
int peer_rank = (my_rank + 1) % 2;
while(count < limit){
filename = fopen("ping_pong_output.txt", "w");
if(my_rank == count % 2){
count++;
MPI_Send(&count, 1, MPI_INT, peer_rank, tag, MPI_COMM_WORLD);
printf("Process %d incremented the count (%d) and sent it to process %d\n\n", my_rank, count, peer_rank);
MPI_Barrier(MPI_COMM_WORLD);
fprintf(filename,"Process %d incremented the count (%d) and sent it to process %d\n", my_rank, count, peer_rank);
} else{
MPI_Barrier(MPI_COMM_WORLD);
MPI_Recv(&count, 1, MPI_INT, peer_rank, tag, MPI_COMM_WORLD,
&status);
MPI_Barrier(MPI_COMM_WORLD);
printf("Process %d received the count from process %d.\n", my_rank, peer_rank);
fprintf(filename,"Process %d received the count.\n", peer_rank);
}
fclose(filename);
}
MPI_Finalize();
return 0;}
欲写入文件的printf的语句的输出,但code为仅输出在最后的同时循环迭代到该文件的最后的printf。如果有人有一个解决这个问题,将不胜AP preciated。
I want the output of the printf statements written to a file, but the code is only outputting the last printf in the final while loop iteration to the file. If anybody has a solution to this problem it would be greatly appreciated.
推荐答案
不要打开您的每一次文件。一旦打开它,并通过文件指针
。这是你的问题。
Do not open your file every time. open it once and pass FILE-POINTER
. This is your problem.
这篇关于写入到一个输出文件在C MPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文