SLURM作业问题:多节点执行时无法正确输出节点主机名
解决SLURM作业节点主机名输出问题
问题原因
你的脚本中srun ./helloworld $%N的写法存在两处错误:
- bash会将
$%识别为无效变量(输出为空),最终传递给程序的参数仅为%N - 即使去掉
$,bash的历史扩展机制会解析%符号,导致srun无法正确触发节点名替换逻辑
解决方案
提供三种可行的解决方式,按需选择:
方式1:修正srun命令的参数传递
用单引号包裹%N,避免bash解析,让srun负责替换节点名:
srun ./helloworld '%N'
或者转义%符号:
srun ./helloworld \%N
方式2:让程序直接读取SLURM环境变量
修改cpp代码,直接读取SLURM为每个任务提供的节点名环境变量(无需传递参数,更可靠):
#include <iostream> #include <cstdlib> int main() { const char* nodeName = std::getenv("SLURMD_NODENAME"); if (nodeName == nullptr) { nodeName = "unknown node"; } std::cout << "Hello World from " << nodeName << std::endl; return 0; }
对应的脚本可简化为:
#!/bin/bash #SBATCH --nodes 2 #SBATCH --ntasks 2 #SBATCH --time=0:01:00 #SBATCH --job-name="hostname" #SBATCH --output=helloworld.out #SBATCH --error=helloworld.er module load gcc srun ./helloworld
方式3:直接在节点上执行hostname命令传递
让srun在每个节点上调用hostname获取主机名,再作为参数传递:
srun ./helloworld $(hostname)
该方式依赖节点上hostname命令的可用性,可靠性略低于前两种。
验证结果
修改后提交作业,输出会符合预期:
Hello World from node_21
Hello World from node_44
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

