How Master is Receiving Other Process Data

Hi,
I have typed a program in master is sending the data to other processes. But master is also able to receive the data sent to other processes. How is it possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include "mpi.h"
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char idstr[128];
char buff[128];
int numprocs;
int myid;
int i;
MPI_Status stat;
/*********************************************
Begin program
*********************************************/
MPI_Init(&argc,&argv);// Initialize
MPI_Comm_size(MPI_COMM_WORLD, &numprocs); // Get # processors
MPI_Comm_rank(MPI_COMM_WORLD, &myid);// Get my rank (id)
if( myid == 0 )
{ // Master
   printf("WE have %d processors\n", numprocs);
   for( i = 1; i < numprocs; i++){
     sprintf(buff, "Hello %d", i);
     MPI_Send(buff, 128, MPI_CHAR, i, 0, MPI_COMM_WORLD);
     //MPI_Send(void *buff, int count, MPI_Datatype type, int dest, int tag, int comm)
   }
   for( i = 1; i < numprocs; i++){
     MPI_Recv(buff, 128, MPI_CHAR, i, 0, MPI_COMM_WORLD, &stat);
     //MPI_Recv(void *buff, int count, MPI_Datatype type, int source, int tag, int comm,MPI_Status *status)
     printf("In master %s\n", buff);
   }
}
else
{ // Slave
MPI_Recv(buff, 128, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &stat);

sprintf(idstr, "in Slave Hello 0, Processor %d is present and accounted for !", myid);
MPI_Send(buff, 128, MPI_CHAR, 0, 0, MPI_COMM_WORLD);

}
MPI_Finalize();
return 0;

}


In my opinion data should be received in the Slave Block but it is being received in the master block. Can somebody please explain me the above code?

I am getting following output:


WE have 4 processors
In master Hello 1
In master Hello 2
In master Hello 3



Zulfi.
Line 38 is currently sending back the contents of buff (which is the "hello" statement just received from the root processor). Did you intend to send idstr defined on line 37 instead?

If you change line 38 to
MPI_Send(idstr, 128, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
then you get (with 4 processors):
WE have 4 processors
In master in Slave Hello 0, Processor 1 is present and accounted for !
In master in Slave Hello 0, Processor 2 is present and accounted for !
In master in Slave Hello 0, Processor 3 is present and accounted for !


I presume that was what you wanted. The root processor does all the outout to screen. The double "in ..." reflects what you wrote on line 30:
printf("In master %s\n", buff);
and the fact that the return message in buff would start "in slave ..." (presuming that you made the changes above).
Last edited on
Hi,
Thanks for removing my confusion. I overlooked "sprintf" in line 37. I thought it was "printf".

God bless you.

Zulfi.
Topic archived. No new replies allowed.