Parallel Computing Lab
5. Write a MPI Program to demonstration of MPI_Send and MPI_Recv.
Save the program as 5.c
#include <mpi.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
int rank, size;
const int MAX_LEN = 100;
char message[MAX_LEN];
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Get the rank of the process
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (size < 2) {
if (rank == 0) {
printf("This program requires at least two processes.\n");
}
MPI_Finalize();
return 0;
}
if (rank == 0) {
// Process 0 sends a message to process 1
strcpy(message, "Hello from process 0!");
MPI_Send(message, strlen(message) + 1, MPI_CHAR, 1, 0, MPI_COMM_WORLD);
printf("Process 0 sent message: %s\n", message);
} else if (rank == 1) {
// Process 1 receives the message from process 0
MPI_Recv(message, MAX_LEN, MPI_CHAR, 0, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
printf("Process 1 received message: %s\n", message);
}
// Finalize the MPI environment
MPI_Finalize();
return 0;
}
Dept. of CSE, JCER, Belagavi Page 10
Parallel Computing Lab
Note: install mpi
sudo apt install -y openmpi-bin libopenmpi-dev
Execution steps
mpicc -o 5 5.c
mpirun -np 2 ./5
Output
Process 0 sent message: Hello from process 0!
Process 1 received message: Hello from process 0!
Dept. of CSE, JCER, Belagavi Page 11