I got my first MPICH2 program up and running in LAN on two PCs. The command that I am typing at the client is:
root@ubuntu:/home# mpiexec -f hosts.cfg -n 4 ./hello
Hello world from process 3 of 4
Hello world from process 2 of 4
Hello world from process 1 of 4
Hello world from process 0 of 4
My program is this:
/* C Example */
#include <mpi.h>
#include <stdio.h>
int main (int argc, char* argv[])
{
int rank, size;
MPI_Init (&argc, &argv); /* starts MPI */
MPI_Comm_rank (MPI_COMM_WORLD, &rank); /* get current process id */
MPI_Comm_size (MPI_COMM_WORLD, &size); /* get number of processes */
printf( "Hello world from process %d of %d\n", rank, size );
MPI_Finalize();
return 0;
}
I locally compiled MPI_hello.c to get executables on each machine.
I want to modify the code so that it must prints something like this:
Hello world from process 3 running on PC2 of 4
Hello world from process 2 running on PC2 of 4
Hello world from process 1 running on PC1 of 4
Hello world from process 0 running on PC1 of 4
PC1 and PC2 are the names of the two PCs my MPI program is supposed to run. So basically I am looking for an API that will fetch the name of the computer along with each process.
How do I do this?
Update
damienfrancois's both answers worked perfectly well. Here is my output:
root@ubuntu:/home# mpiexec -f hosts.cfg -n 4 ./hello
Hello world from process 1 running on PC1 of 4
Hello world from process 3 running on PC1 of 4
Hello world from process 2 running on PC2 of 4
Hello world from process 0 running on PC2 of 4
The assignment of the process id is a matter of affinity , which has to be mentioned in the hosts.cfg file
One option is to use the gethostname(2) system call:
/* C Example */
#include <mpi.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
int rank, size;
int buffer_length = 512;
char hostname[buffer_length];
MPI_Init (&argc, &argv); /* starts MPI */
MPI_Comm_rank (MPI_COMM_WORLD, &rank); /* get current process id */
MPI_Comm_size (MPI_COMM_WORLD, &size); /* get number of processes */
gethostname(hostname, buffer_length); /* get hostname */
printf( "Hello world from process %d running on %s of %d\n", rank, hostname, size );
MPI_Finalize();
return 0;
}
Another is to use MPI_Get_processor_name:
/* C Example */
#include <mpi.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
int rank, size;
int buffer_length = MPI_MAX_PROCESSOR_NAME;
char hostname[buffer_length];
MPI_Init (&argc, &argv); /* starts MPI */
MPI_Comm_rank (MPI_COMM_WORLD, &rank); /* get current process id */
MPI_Comm_size (MPI_COMM_WORLD, &size); /* get number of processes */
MPI_Get_processor_name(hostname, &buffer_length); /* get hostname */
printf( "Hello world from process %d running on %s of %d\n", rank, hostname, size );
MPI_Finalize();
return 0;
}