I have written some basic programs in C using MPI. Some of them used to work untill yesterday. Today I get segmentation faults from most of them. One goes an infinite loop, but I've no loops in it. This is really making me mad.
This is the program that goes on loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "mpi.h"
int main(int argc, char *argv[]) {
int rank, nprocs, maxn, i, j, local_counter, global_counter;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm comm;
MPI_Comm_size(MPI_COMM_WORLD, &nprocs); /* Number of processes */
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int N = 0; /*Number of prime numbers I've found*/
if (rank == 0){
printf("What is the maximum number to check?");
scanf("%d", &maxn);
}
MPI_Finalize();
return 0;
}
Using scanf
you are trying to read from stdin
which is generally not admissible in MPI and on my system (a computer cluster) it causes the program to stall and run "infinitely".
What you need to do is either read your value from a file or as a command line argument.
Here is the command line argument version:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "mpi.h"
int main(int argc, char *argv[]) {
int rank, nprocs, maxn, i, j, local_counter, global_counter;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm comm;
/* Number of processes */
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/* Number of prime numbers I've found */
int N = 0;
// Usage check
if(argc!=2){
printf("Error\n");
printf("Syntax mpi_in <Maximum number to check>\n");
MPI_Finalize();
exit(1);
}
maxn = atoi(argv[1]);
if (rank == 0){
printf("Maximum number to check is: %d \n", maxn);
}
MPI_Finalize();
return 0;
}
In the command line argument version you may as well make all the processes unpack the argument, here for a demonstration process 0 prints the value.
Calling MPI_Init
cleans the argument list so after that the program uses argc
and argv[]
as if it is a non-MPI program. This is apparently not a guaranteed behavior, but it works on two different systems I'm using. In this case argc
will be 2 since the first argument is always the name of the program. You can run it from the terminal as, for instance with 5 processes,
mpirun -np 5 mpi_in 300
Note that since argv
is an array of pointers to strings, the program needs atoi
to convert the number from string to int.