建立两个独立应用程序之间的连接

主进程为每个应用程序生成一个进程,生成服务器和客户端应用程序。服务器打开一个端口,客户端连接到该端口。然后客户端使用 MPI_Send 向服务器发送数据,以验证连接是否已建立。

master.c

#include "mpi.h"

int main(int argc, char *argv[])
{   
   MPI_Init(&argc, &argv);

   MPI_Comm intercomm;
   // Spawn two applications with a single process for each application.
   // Server must be spawned before client otherwise the client will complain at MPI_Lookup_name().
   MPI_Comm_spawn("server", MPI_ARGV_NULL, 1, MPI_INFO_NULL, 0, MPI_COMM_SELF, &intercomm, MPI_ERRCODES_IGNORE);
   MPI_Comm_spawn("client", MPI_ARGV_NULL, 1, MPI_INFO_NULL, 0, MPI_COMM_SELF, &intercomm, MPI_ERRCODES_IGNORE);
   
   MPI_Finalize();
   return 0;
}

server.c

#include "mpi.h"
#include <stdio.h>

int main(int argc, char *argv[])
{  
   MPI_Init(&argc, &argv);

   // Open port.
   char port_name[MPI_MAX_PORT_NAME];
   MPI_Open_port(MPI_INFO_NULL, port_name);

   // Publish port name and accept client.
   MPI_Comm client;
   MPI_Publish_name("name", MPI_INFO_NULL, port_name);
   MPI_Comm_accept(port_name, MPI_INFO_NULL, 0, MPI_COMM_WORLD, &client);
   
   // Receive data from client.
   int recvbuf;
   MPI_Recv(&recvbuf, 1, MPI_INT, 0, 0, client, MPI_STATUS_IGNORE);
   printf("recvbuf = %d\n", recvbuf);

   MPI_Unpublish_name("name", MPI_INFO_NULL, port_name);

   MPI_Finalize();
   return 0;
}

client.c

#include "mpi.h"

int main(int argc, char *argv[])
{   
   MPI_Init(&argc, &argv);

   // Look up for server's port name.
   char port_name[MPI_MAX_PORT_NAME];
   MPI_Lookup_name("name", MPI_INFO_NULL, port_name);
   
   // Connect to server.
   MPI_Comm server;
   MPI_Comm_connect(port_name, MPI_INFO_NULL, 0, MPI_COMM_SELF, &server);

   // Send data to server.
   int sendbuf = 3;
   MPI_Send(&sendbuf, 1, MPI_INT, 0, 0, server);
   
   MPI_Finalize();
   return 0;
}

命令行

mpicc master.c -o master_program
mpicc server.c -o server
mpicc client.c -o client
mpirun -n 1 master_program