2012-06-24 48 views
8

我使用gccOpenMPI。我通常運行使用mpirun包裝MPI程序 - 例如,運行OpenMPI程序沒有mpirun

mpirun -np 4 myprogram 

啓動4個進程。

但是,我想知道是否可以輕鬆生成一個二進制文件,這將自動執行(也許有一些硬編碼選項,如-np 4)。

我知道我可以寫一個C包裝調用我的程序,如下列:

#include <stdlib.h> 
#include <unistd.h> 

int main() { 
     char *options[] = { "mpirun", "-np", "4", "myprogram" }; 

     execvp("mpirun", options); 
     /* Ignoring return value to keep example simple */ 

     return EXIT_SUCCESS; 
} 

但這似乎有點笨拙,我結束了兩個可執行文件,而不是一個。

我試圖顯式鏈接MPI庫,例如

gcc -o myprogram -I/usr/lib/openmpi/include/ \ 
    -lmpi -L/usr/lib/openmpi/lib/ myprogram.c 

但是當我運行生成的可執行文件,MPI_Comm_size集零爲組的大小(因爲如果我給了-np 0作爲參數)。我可以使用環境變量或其他方式來傳遞組大小嗎?或者,還有另一種方法來構建一個單一可執行的MPI程序(使用Linux和gcc)?

+0

它可以做到,但我不知道如何從頭頂上。 我知道一些我遇到過的程序是這樣做的。這裏沒有真正的魔法,它只是在幕後做了一堆事情,你也可以自己做。 –

+0

我是否理解正確 - 你想跳過'mpirun'或者你想以某種方式自動調用'mpirun'? –

+0

@Hristo Iliev:如果我有一個靜態二進制文件,那將會很好。 – Jay

回答

6

如果我沒有得到它,你想有一個自推出MPI可執行文件。正如我在評論中所寫的那樣,您可以使用一個特殊選項,使您的代碼在提供時執行mpirun(例如)。 -launchmpi。使用Open MPI,它更容易,因爲它將特殊的環境變量導出到已啓動的MPI進程中,例如, OMPI_COMM_WORLD_RANK。如果此變量存在於環境中,那麼您知道程序是從mpirun啓動的,而不是直接啓動。

int main (int argc, char **argv) 
{ 
    int perform_launch = 0; 
    // Scan argv[] for special option like "-launchmpi" 
    // and set perform_launch if found 

    if (perform_launch || getenv("OMPI_COMM_WORLD_RANK") == NULL) 
    { 
     // #args = argc + 3 ("mpirun -np 4" added) + NULL 
     // #args should be reduced by one if "-launchmpi" is present 
     char **args = (char **)calloc(
      argc + (perform_launch ? 3 : 4), 
      sizeof(char *)); 
     args[0] = "mpirun"; 
     args[1] = "-np"; 
     args[2] = "4"; 
     // Copy the entire argv to the rest of args but skip "-launchmpi" 

     execvp("mpirun", args); 

     return EXIT_SUCCESS; 
    } 

    // Proceed as regular MPI code 
    MPI_Init(&argc, &argv); 
    ... 
    // Magic happens here 
    ... 
    MPI_Finalize(); 

    return EXIT_SUCCESS; 
} 

如果你想控制在MPI工作進程數,你可以提供它作爲一個額外的arugment,例如:你可以在一個檢查這個結合這兩種方法-launchmpi 12或環境變量,並在上面的代碼中使用它的值而不是"4"

請注意,如果沒有mpirun,MPI可執行文件通常無法啓動。後者是MPI運行時的一個組成部分,它還可以啓動多個MPI可執行文件。在編譯任何MPI編譯器包裝時,您也總是明確鏈接到MPI庫(嘗試mpicc -showme)。雖然您可以靜態鏈接MPI庫(不推薦,請參閱here),但仍需要mpirun才能運行MPI作業 - AFAIK無法在程序中嵌入mpirun功能,至少不能在Open MPI中嵌入。

+0

感謝您的回覆 - 這真的很有用! – Jay

1

你可以用bash腳本做到這一點:

 
# If you change this script has executable (chmod +x script_name) 
# and if you have the current path in the PATH variable (add export PATH=.:$PATH in your .bashrc) 
#Then, you can run this has: script_name program_args 

mpirun -np 4 your_executable_name "[email protected]" 
+1

你幾乎肯定需要''$ @''',而不是'$ *',否則你會在分詞時破壞參數。 –

+0

謝謝@ChrisDown我更正了我的答案。 – RSFalcon7

+1

你的論點仍然會被打亂。引號很重要。 –