/* nearly the simplest possible message-passing program: process 0 sends a message, and process 1 receives and prints it. */ #include #include #include "mpi.h" /* MPI header file */ int main(int argc, char *argv[]) { int nprocs; int myid; int buff[2]; int bufflen = 2; int mytag = 0; int source; int dest; MPI_Status status; /* initialize for MPI */ if (MPI_Init(&argc, &argv) != MPI_SUCCESS) { printf("MPI initialization error\n"); exit(EXIT_FAILURE); } /* get number of processes */ (void) MPI_Comm_size(MPI_COMM_WORLD, &nprocs); if (nprocs != 2) { printf("number of processes must be 2\n"); exit(EXIT_FAILURE); } /* get this process's number (ranges from 0 to nprocs - 1) */ (void) MPI_Comm_rank(MPI_COMM_WORLD, &myid); if (myid == 0) { /* in process 0: send message to process 1 */ buff[0] = 10; buff[1] = 20; dest = 1; if (MPI_Send(buff, bufflen, MPI_INTEGER, dest, mytag, MPI_COMM_WORLD) != MPI_SUCCESS) { printf("error sending message\n"); exit(EXIT_FAILURE); } printf("process 0 sent %d %d\n", buff[0], buff[1]); } else { /* in process 1: receive message from process 0 and print */ source = 0; if (MPI_Recv(buff, bufflen, MPI_INTEGER, source, mytag, MPI_COMM_WORLD, &status) != MPI_SUCCESS) { printf("error receiving message\n"); exit(EXIT_FAILURE); } printf("process 1 received %d %d\n", buff[0], buff[1]); } /* clean up for MPI */ (void) MPI_Finalize(); return EXIT_SUCCESS; }