2

我的第一个 MPICH2 程序在两台 PC 上的 LAN 中启动并运行。我在客户端输入的命令是:

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

我的程序是这样的:

/* 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;
}

我在本地编译 MPI_hello.c 以在每台机器上获取可执行文件。

我想修改代码,使其必须打印如下内容:

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 和 PC2 是我的 MPI 程序应该运行的两台 PC 的名称。所以基本上我正在寻找一个 API 来获取计算机的名称以及每个进程。

我该怎么做呢?

更新

damienfrancois 的两个答案都非常有效。这是我的输出:

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

进程id的分配是一个affinity的问题,必须在hosts.cfg文件中提到

4

1 回答 1

2

一种选择是使用gethostname(2)系统调用:

/* 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;
}

另一种是使用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;
}
于 2013-10-26T19:07:32.827 回答