2013-10-26 37 views
2

我在兩臺PC上啓動並運行了LAN中的第一個MPICH2程序。 ,我在客戶端輸入的命令是:MPICH2:獲取進程計算機名稱的API

[email protected]:/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程序應該運行的名字。 所以基本上我正在尋找一個API來獲取計算機的名稱以及每個進程。

我該怎麼做?

更新

damienfrancois的兩個答案非常行之有效。這裏是我的輸出:

[email protected]:/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文件

回答

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