0% found this document useful (0 votes)
6 views2 pages

MPI_Send and MPI_Recv Example Code

The document provides a simple MPI program written in C that demonstrates the use of MPI_Send and MPI_Recv for inter-process communication. It includes code for sending a message from process 0 to process 1 and instructions for compiling and executing the program using MPI. Additionally, it notes the requirement of having at least two processes to run the program successfully.

Uploaded by

yashdd1110
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

MPI_Send and MPI_Recv Example Code

The document provides a simple MPI program written in C that demonstrates the use of MPI_Send and MPI_Recv for inter-process communication. It includes code for sending a message from process 0 to process 1 and instructions for compiling and executing the program using MPI. Additionally, it notes the requirement of having at least two processes to run the program successfully.

Uploaded by

yashdd1110
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

You might also like