Maybe it can‘t be run ,but it just provides a thinking way and mpi api overview.
#include "mpi.h"
#include <stdio.h>
#include <unistd.h>
#define nodeNameLength 20
int main(int argc, char *argv[])
{
int rank,nproc;
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &nproc);
MPI_Comm_rank( MPI_COMM_WORLD, &rank);
char currentNodeName[nodeNameLength];
if(-1==gethostname(currentNodeName,sizeof(currentNodeName)))
{
perror("gethostname error !");
return;
}
char numStr[nodeNameLength];
int i=-1;//************************just a count variable
for(i=4;i<strlen(currentNodeName);i++)
{numStr[i]=currentNodeName[i];//numStr is a string which only includes number
}
numStr[i]='\0';
int num =atoi(numStr);//convert string to number
int allName[nproc];
//root process get information of nodes.
MPI_Gather(&num, 1, MPI_BYTE, allName, nproc, MPI_BYTE, 0,MPI_COMM_WORLD);
int rankofnode[nproc];
if(0==rank)
{for(i=0;i<nproc;i++)
{
int noderank=0;
int j=-1;
for(j=0;j<=i;j++)
{
if(allName[i]==allName[j])
noderank++;
}
rankofnode[i]=noderank;
}
}
MPI_Bcast(rankofnode,,MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Comm myWorld,nodeWorld;
MPI_Comm_dup(MPI_COMM_WORLD,&myWorld);
MPI_Common_split(myWorld,num,rankofnode[rank],&nodeWorld);
int members[nproc];
int head_num=0;
for(i=0;i<nproc;i++)
{if(0==rankofnode[i])
{
members[head_num]=i;//members store the set of head member
head_num++;
}
}
MPI_Group group_world,head_group;
MPI_Comm head_comm;
MPI_COMM_group(MPI_COMM_WORLD,&group_world);
MPI_Group_incl(group_world,head_num,members,&head_group);
MPI_Comm_create(MPI_COMM_WORLD,head_group,&head_comm);
//At now ,The node communication and head head communication are created.
MPI_Finalize();
return 0;
}