MPICH2:用于获取进程计算机名称的API

时间:2013-10-26 10:05:05

标签: mpi mpich

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

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的赋值是亲和力问题,必须在hosts.cfg文件中提及

1 个答案:

答案 0 :(得分: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;
}