bash 脚本中的 mpirun 命令与 MPI 代码之间的连接

connection between mpirun command in bash script and MPI code

我想知道如何在 bash 脚本 (slurm) 中设置变量并在 C 语言的 MPI 程序中使用该变量,反之亦然。 例如: 在 test-mpi.c 中定义 int i; …… 然后在 bash 脚本中这样使用它:

if (i=o)
  mpirun --map-by ppr:1:socket ./test-mpi
if (i=1)
  mpirun --map-by ppr:1:node ./test-mpi  

实际上,我想使用 ppr:1:socket 来完成我的一部分代码,而另一部分使用 ppr:1:node

此外,是否可以在 MPI 程序中将进程映射到套接字而不是在 bash 脚本中进行映射?

如有任何建议,我们将不胜感激。

编辑:

这样用argc,argv可以吗:

for (count =0; count < argc; count++){
 if (argv[i] == "state1"){
  for (....)
      do something

for (count =0; count < argc; count++){
 if (argv[i] == "state2"){
  for (....)
      do something

您可以向您的应用程序添加一个命令行标志,例如:

int main(int argc, char* argv[]) {
    // argc is the number of arguments, including the executable.
    // so 2 means one argument
    // check if that argument equals "--dump-i"
    if (argc == 2 && 0 == strcmp(argv[1], "--dump-i")) {
        printf("%d", i);
        return 0;
    }
    MPI_Init(NULl, NULL);
    ...
}

并且在您的 bash 脚本中是这样的:

i = $(./test-mpi --dump-i)
if [ "$i" == "1" ]; then
    mpirun --map-by ppr:1:socket ./test-mpi
else
    mpirun --map-by ppr:1:node ./test-mpi  
fi

(未经测试)

但我怀疑如果您提供更多关于您实际想做的事情的细节,会有更好的解决方案。

编辑

到 运行 在 slurm 中并行执行多个作业步骤:

# Make sure to restrict the resources, such that 
# the entire job has enough to run both steps simultaneously.
# The ampersand launches the jobs in the background such that
# they are not executed sequentially
srun -n ... --map-by ppr:1:socket ./test-mpi --first-loop &
srun -n ... --map-by ppr:1:node ./test-mpi --second-loop &

我由你来实现类似于上面示例的命令行开关。您也可以构建为二进制文件。

编辑2

针对您的编辑,您不能将 C 字符串与 == 进行比较,您需要使用 strcmpstrncmp。对于更复杂的命令行参数解析,请查看 getopt_long.