Roman Pavlov Roman Pavlov - 25 days ago 9
C++ Question

MPI ignores cin

I've write following code. It intends to read number from console (to

data
variable) and send it to all other processes. But
cin >> data
just ignored.

#include <mpi.h>
#include <iostream>
#include <stdio.h>

using namespace std;

int main(int argc, char* argv[]) {
int rank, n;
int i;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &n);
int data = 322; // magic number 322 just for initialisation
if (rank == 0)
{
cout << "From which process do you want to transfer data?" << endl;
cin >> i;
MPI_Send(&i, 1, MPI_INT, rank+1, 0, MPI_COMM_WORLD);
}
else
{
MPI_Recv(&i, 1, MPI_INT, rank-1, 0, MPI_COMM_WORLD, &status);

if (rank < n - 1)
MPI_Send(&i, 1, MPI_INT, rank+1, 0, MPI_COMM_WORLD);

if(rank == i) {
cout << "Process #"<< rank <<" waiting data to send. Please enter." << endl;
cin >> data; //doesn't work

for(int j = 0; j < n; j++)
if(j != i)
MPI_Send(&data, 1, MPI_INT, j, 7, MPI_COMM_WORLD);
}
else {
int pata;
MPI_Recv(&pata, 1, MPI_INT, i, 7, MPI_COMM_WORLD, &status);
cout << "Process "<< rank <<" received data (" << pata << ") from process #" << i << endl;
}
}
MPI_Finalize( );
}


Console looks something like:

From which process do you want to transfer data?
2
Process #2 waiting data to send. Please enter.
Process 1 received data (322) from process #2
Process 3 received data (322) from process #2


I've already tried
cin.clear()
and
cin.ignore()
.

Answer Source

stdin is generally redirected from mpirun/mpiexec to rank 0.

There might be options (that depend on which implementation you are running) to redirect to the rank of your choice, and/or to redirect to all the ranks.

Bottom line, i do not think what you are trying is achievable.